Ejemplo n.º 1
0
        private static string ExtractJsonResponse(WebResponse response)
        {
            GetRateLimits(response);

            var responseStream = response.GetResponseStream();
            if (responseStream == null)
            {
                throw new StackExchangeException("Response stream is empty, unable to continue");
            }

            string json;
            using (var outStream = new MemoryStream())
            {
                using (var zipStream = new GZipStream(responseStream, CompressionMode.Decompress))
                {
                    zipStream.CopyTo(outStream);
                    outStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new StreamReader(outStream, Encoding.UTF8))
                    {
                        json = reader.ReadToEnd();
                    }
                }
            }

            return json;
        }
Ejemplo n.º 2
0
        public static string GzipDecompress(string fileFullName)
        {
            var retName = string.Empty;
            if (!File.Exists(fileFullName))
                return retName;

            var fi = new FileInfo(fileFullName);

            using (var fs = fi.OpenRead())
            {
                var dName = fi.DirectoryName;
                if (string.IsNullOrWhiteSpace(dName))
                {
                    dName = TempDirectories.Root;
                }
                var cName = fi.FullName;
                var nName = Path.GetFileNameWithoutExtension(cName);
                var nFName = Path.Combine(dName, nName);

                using (var dFs = File.Create(nFName))
                {
                    using (var gzipStream = new GZipStream(fs, CompressionMode.Decompress))
                    {
                        gzipStream.CopyTo(dFs);
                    }
                }
                retName = nFName;
            }

            return retName;
        }
Ejemplo n.º 3
0
        private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var name = new AssemblyName(args.Name).Name.Replace('-', '.');
            if (name.StartsWith(m_rootNamespace)) return null;

            for (int i = 0; i < m_resourceName.Length; ++i)
            {
                if (m_resourceName[i].Contains(name))
                {
                    byte[] buff;

                    using (var comp     = new MemoryStream((byte[])m_resourceMethod[i].GetValue(null, null)))
                    using (var gzip     = new GZipStream(comp, CompressionMode.Decompress))
                    using (var uncomp   = new MemoryStream(4096))
                    {
                        gzip.CopyTo(uncomp);
                        buff = uncomp.ToArray();
                    }

                    return Assembly.Load(buff);
                }
            }

            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        public static void Decompress(this FileInfo fileInfo)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fileInfo.OpenRead())
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.
                string curFile = fileInfo.FullName;
                string origName = curFile.Remove(curFile.Length -
                        fileInfo.Extension.Length);

                //Create the decompressed file.
                using (FileStream outFile = File.Create(origName))
                {
                    using (GZipStream Decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream 
                        // into the output file.
                        Decompress.CopyTo(outFile);

                        Console.WriteLine("Decompressed: {0}", fileInfo.Name);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        private static int Main(string[] args)
        {
            // Get embedded compressed resource stream and decompress data
            Stream byteStream = new MemoryStream();
            using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("PackedStarter.NetRevisionTool.exe.gz"))
            using (GZipStream zip = new GZipStream(resourceStream, CompressionMode.Decompress, true))
            {
                zip.CopyTo(byteStream);
            }

            // Copy decompressed stream to an array
            byte[] bytes = new byte[byteStream.Length];
            byteStream.Seek(0, SeekOrigin.Begin);
            byteStream.Read(bytes, 0, bytes.Length);

            // Load embedded assembly
            Assembly assembly = Assembly.Load(bytes);

            // Find and invoke Program.Main method
            Type programType = assembly.GetType("NetRevisionTool.Program");
            MethodInfo mainMethod = programType.GetMethod("Main");
            object returnValue = mainMethod.Invoke(null, new object[] { args });

            // Pass on return code
            if (returnValue is int)
            {
                return (int) returnValue;
            }
            return 0;
        }
Ejemplo n.º 6
0
        public static ISavegame Deserialize(Stream stream)
        {
            if (stream == null) throw new ArgumentNullException(nameof(stream));

            if (stream.Position != 0)
                stream.Seek(0, SeekOrigin.Begin);

            var checkBuffer = new byte[2];
            stream.Read(checkBuffer, 0, 2);
            stream.Seek(0, SeekOrigin.Begin);

            if (checkBuffer.SequenceEqual(new byte[] {0x1f, 0x8b}))
            {
                using (var gZipStream = new GZipStream(stream, CompressionMode.Decompress))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        gZipStream.CopyTo(memoryStream);
                        return Deserialize(Encoding.UTF8.GetString(memoryStream.ToArray()));
                    }
                }
            }

            if (stream is MemoryStream)
            {
                var memoryStream = (MemoryStream) stream;
                return Deserialize(Encoding.UTF8.GetString(memoryStream.ToArray()));
            }

            using (var memoryStream = new MemoryStream())
            {
                stream.CopyTo(memoryStream);
                return Deserialize(Encoding.UTF8.GetString(memoryStream.ToArray()));
            }
        }
Ejemplo n.º 7
0
		public ImageDataResult TryGetImageData(out byte[] result)
		{
			result = null;
			if(Compression != CompressionType.None && Compression != CompressionType.Gzip)
			{
				return ImageDataResult.UnsupportedCompressionFormat;
			}
			if(CRC != UImageReader.GzipCrc32(image))
			{
				return ImageDataResult.BadChecksum;
			}
			result = new byte[image.Length];
			Array.Copy(image, result, result.Length);
			if(Compression == CompressionType.Gzip)
			{
				using(var stream = new GZipStream(new MemoryStream(result), CompressionMode.Decompress))
				{
					using(var decompressed = new MemoryStream())
					{
						stream.CopyTo(decompressed);
						result = decompressed.ToArray();
					}
				}
			}
			return ImageDataResult.OK;
		}
Ejemplo n.º 8
0
            public void CompressedTheContentIfGzipIsProvidedOnTheHeader()
            {
                GZippedContent     gzippedContent     = new GZippedContent(new JsonContent(new { test = "test" }));
                HttpConnectRequest request            = CreatePostRequest(content: gzippedContent);
                HttpRequestMessage httpRequestMessage = _middleware.BuildRequestMessageTester(request);
                var content       = httpRequestMessage.Content;
                var contentHeader = content.Headers.SingleOrDefault(h => h.Key == "Content-Encoding");

                contentHeader.Should().NotBeNull();
                contentHeader.Value.SingleOrDefault(v => v == "gzip").Should().NotBeNull();
                content.Should().NotBeNull();

                var stream = content.ReadAsStreamAsync().Result;

                var serializer = new JsonSerializer();

                string jsonString = "";

                using (System.IO.MemoryStream output = new System.IO.MemoryStream())
                {
                    using (System.IO.Compression.GZipStream sr = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress))
                    {
                        sr.CopyTo(output);
                    }

                    jsonString = Encoding.UTF8.GetString(output.GetBuffer(), 0, (int)output.Length);
                }

                JObject json = JObject.Parse(jsonString);

                json["test"].ToString().Should().Be("test");
            }
Ejemplo n.º 9
0
        public static PssgFile Open(Stream stream)
        {
            PssgFileType fileType = PssgFile.GetPssgType(stream);

            if (fileType == PssgFileType.Pssg)
            {
                return PssgFile.ReadPssg(stream, fileType);
            }
            else if (fileType == PssgFileType.Xml)
            {
                return PssgFile.ReadXml(stream);
            }
            else // CompressedPssg
            {
                using (stream)
                {
                    MemoryStream mStream = new MemoryStream();

                    using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress))
                    {
                        gZipStream.CopyTo(mStream);
                    }

                    mStream.Seek(0, SeekOrigin.Begin);
                    return PssgFile.ReadPssg(mStream, fileType);
                }
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Decompresses the given data stream from its source ZIP or GZIP format.
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        internal static byte[] Inflate(Stream dataStream)
        {
            byte[] outputBytes    = null;
            var    zipInputStream = new ZipInputStream(dataStream);

            if (zipInputStream.CanDecompressEntry)
            {
                MemoryStream zipoutStream = new MemoryStream();
                zipInputStream.CopyTo(zipoutStream);
                outputBytes = zipoutStream.ToArray();
            }
            else
            {
                try
                {
                    dataStream.Seek(0, SeekOrigin.Begin);
                    #if !WINDOWS_PHONE
                    var gzipInputStream = new GZipInputStream(dataStream, CompressionMode.Decompress);
                    #else
                    var gzipInputStream = new GZipInputStream(dataStream);
                                        #endif

                    MemoryStream zipoutStream = new MemoryStream();
                    gzipInputStream.CopyTo(zipoutStream);
                    outputBytes = zipoutStream.ToArray();
                }

                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
            }

            return(outputBytes);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Metodo que descomprime un fichero
        /// </summary>
        /// <param name="fi">Informacion del fichero descomprimido</param>
        public static void Decompress(FileInfo fi)
        {
            // Get the stream of the source file.
            using (var inFile = fi.Open(FileMode.Open, FileAccess.ReadWrite))
            {
                // Get original file extension, for example
                // "doc" from report.doc.gz.
                var curFile = fi.FullName;
                var origName = curFile.Remove(curFile.Length -
                        fi.Extension.Length);

                //Create the decompressed file.
                using (var outFile = File.Create(origName))
                {
                    using (var decompress = new GZipStream(inFile,
                            CompressionMode.Decompress))
                    {
                        // Copy the decompression stream
                        // into the output file.
                        decompress.CopyTo(outFile);
                        decompress.Close();
                    }

                    outFile.Close();
                }

                inFile.Close();
            }
        }
Ejemplo n.º 12
0
 public static void Uncompress(Stream input, Stream output)
 {
     using (var zinput = new GZipStream(input, CompressionMode.Decompress, true))
     {
         zinput.CopyTo(output);
     }
 }
        private static void ExtractAssembly(bool is64bit)
        {
            var p = Path.Combine(OutputPath, is64bit ? "x64" : "x86", "xxhash.dll");
            if(!Directory.Exists(Path.GetDirectoryName(p)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(p));
            }
            if (!File.Exists(p))
            {
                string resourceName = string.Format("XXHashSharp.{0}.xxhash.dll.gz", is64bit ? "x64" : "x86");

                using (var s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
                {
                    using (var gz = new GZipStream(s, CompressionMode.Decompress))
                    {
                        using (var fs = new FileStream(p, FileMode.Create, FileAccess.Write))
                        {
                            gz.CopyTo(fs);
                            fs.Flush(true);
                        }
                    }
                }
            }
            LoadLibrary(p);
        }
Ejemplo n.º 14
0
        /// <summary>
        ///     <para> --- </para>
        ///     <para> Initializes FFmpeg.exe; Ensuring that there is a copy</para>
        ///     <para> in the clients temp folder & isn't in use by another process.</para>
        /// </summary>
        public Engine()
        {
            string ffmpegDirectory = "" + Path.GetDirectoryName(FFmpegFilePath);

            if (!Directory.Exists(ffmpegDirectory)) Directory.CreateDirectory(ffmpegDirectory);

            if (File.Exists(FFmpegFilePath))
            {
                if (!Document.IsFileLocked(new FileInfo(FFmpegFilePath))) return;

                Process[] ffmpegProcesses = Process.GetProcessesByName("ffmpeg");
                if (ffmpegProcesses.Length > 0)
                    foreach (Process process in ffmpegProcesses)
                    {
                        // pew pew pew...
                        process.Kill();
                        // let it die...
                        Thread.Sleep(200);
                    }
            }
            else
            {
                Stream ffmpegStream = Assembly.GetExecutingAssembly()
                    .GetManifestResourceStream("MediaToolkit.Resources.FFmpeg.exe.gz");

                if (ffmpegStream == null) throw new Exception("FFMpeg GZip stream is null");

                using (var tempFileStream = new FileStream(FFmpegFilePath, FileMode.Create))
                using (var gZipStream = new GZipStream(ffmpegStream, CompressionMode.Decompress))
                {
                    gZipStream.CopyTo(tempFileStream);
                }
            }
        }
Ejemplo n.º 15
0
        public ManagedBitmap(string fileName)
        {
            try
            {
                byte[] buffer = new byte[1024];
                using (var fd = new MemoryStream())
                using (Stream csStream = new GZipStream(File.OpenRead(fileName), CompressionMode.Decompress))
                {
                    csStream.CopyTo(fd);
                    buffer = fd.ToArray();
                }

                Width = buffer[4] << 8 | buffer[5];
                Height = buffer[6] << 8 | buffer[7];
                _colors = new Color[Width * Height];
                int start = 8;
                for (int i = 0; i < _colors.Length; i++)
                {
                    _colors[i] = Color.FromArgb(buffer[start], buffer[start + 1], buffer[start + 2], buffer[start + 3]);
                    start += 4;
                }
            }
            catch
            {
                LoadedOk = false;
            }
        }
Ejemplo n.º 16
0
 public static void Decompress(Stream inputStream, Stream outputStream)
 {
     using (GZipStream zip = new GZipStream(inputStream, CompressionMode.Decompress))
     {
         zip.CopyTo(outputStream);
     }
 }
Ejemplo n.º 17
0
        private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var asm = args.RequestingAssembly ?? Assembly.GetExecutingAssembly();
            string asmname = asm.GetName().Name.Split('.').FirstOrDefault();
            var tgt = new AssemblyName(args.Name);
            var tgtname = asmname + "." + tgt.Name + ".dll";
            var resname = asm.GetManifestResourceNames().FirstOrDefault(n => string.Compare(n, tgtname, true) == 0);
            if (!string.IsNullOrWhiteSpace(resname))
            {
                using (var strm = asm.GetManifestResourceStream(resname))
                {
                    byte[] data = new byte[strm.Length];
                    strm.Read(data, 0, (int)strm.Length);
                    return Assembly.Load(data);
                }
            }

            resname = asm.GetManifestResourceNames().FirstOrDefault(n => string.Compare(n, tgtname + ".gz", true) == 0);
            if (!string.IsNullOrWhiteSpace(resname))
            {
                using (var strm = asm.GetManifestResourceStream(resname))
                using (var decom = new GZipStream(strm, CompressionMode.Decompress, true))
                {
                    byte[] data = null;
                    using (var ms = new MemoryStream())
                    {
                        decom.CopyTo(ms);
                        data = ms.ToArray();
                    }
                    return Assembly.Load(data);
                }
            }

            return null;
        }
Ejemplo n.º 18
0
        /// <summary> Loads a TrigradCompressed image from a stream. </summary>
        public TrigradCompressed(Stream s)
        {
            using (GZipStream dezipper = new GZipStream(s, CompressionMode.Decompress))
            using (BinaryReader reader = new BinaryReader(new MemoryStream()))
            {
                dezipper.CopyTo(reader.BaseStream);
                reader.BaseStream.Position = 0;

                Width = reader.ReadUInt16();
                Height = reader.ReadUInt16();

                List<Color> colorIndex = new List<Color>();
                Dictionary<Point, ushort> pointIndex = new Dictionary<Point, ushort>();

                ushort colors = reader.ReadUInt16();
                for (int i = 0; i < colors; i++)
                {
                    colorIndex.Add(Color.FromArgb(reader.ReadByte(), reader.ReadByte(), reader.ReadByte()));
                }
                uint points = reader.ReadUInt32();
                for (int i = 0; i < points; i++)
                {
                    Point p = new Point(reader.ReadUInt16(), reader.ReadUInt16());
                    ushort index = reader.ReadUInt16();
                    pointIndex.Add(p, index);
                }

                foreach (var pair in pointIndex)
                {
                    SampleTable.Add(pair.Key, colorIndex[pair.Value]);
                }

            }
        }
        static void Decompress_gz(string gz_file)
        {
            FileStream OriginalFileStream = File.OpenRead(gz_file); // This Returns a file stream to read.

            string extension = Path.GetExtension(gz_file); // This Gets the Extension of the File.
            string final_filename = gz_file.Substring(0, gz_file.Length - extension.Length); // Getting the File Name without the File Extension.

            final_filename = final_filename + ".txt";

            FileStream decompressedFileStream = File.Create(final_filename); // Creating a File to Store the Decompressed File

            GZipStream decompressionStream = new GZipStream(OriginalFileStream, CompressionMode.Decompress); // This sets the Decompression of the Original Compressed FileStream.

            decompressionStream.CopyTo(decompressedFileStream); // Copies the Decompressed File Stream to the desired file.

            // Closing all the File Handles
            decompressionStream.Close();
            decompressedFileStream.Close();
            OriginalFileStream.Close();

            // Parsing the Decompressed File.
            Parse_File(final_filename);
            Console.WriteLine("Decompressed File Name is " + final_filename);

            return;
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Decompresses stream using GZip. Returns decompressed Stream.
        /// Returns null if stream isn't compressed.
        /// </summary>
        /// <param name="compressedStream">Stream compressed with GZip.</param>
        public static MemoryStream DecompressStream(Stream compressedStream)
        {
            MemoryStream newStream = new MemoryStream();
            compressedStream.Seek(0, SeekOrigin.Begin);

            GZipStream Decompressor = null;
            try
            {
                Decompressor = new GZipStream(compressedStream, CompressionMode.Decompress, true);
                Decompressor.CopyTo(newStream);
            }
            catch (InvalidDataException invdata)
            {
                return null;
            }
            catch(Exception e)
            {
                throw;
            }
            finally
            {
                if (Decompressor != null)
                    Decompressor.Dispose();
            }

            return newStream;
        }
 /// <inheritdoc />
 public byte[] Decompress(byte[] data)
 {
     var output = new MemoryStream();
     using (var stream = new GZipStream(new MemoryStream(data), CompressionMode.Decompress))
         stream.CopyTo(output);
     return output.ToArray();
 }
        static void Assemble(List<string> files, string destinationDirectory)
        {
            if (destinationDirectory.LastIndexOf('\\') != destinationDirectory.Length - 1)
            {
                destinationDirectory += "\\";
            }

            foreach (string filePath in files)
            {

                string fileName = filePath.Substring(filePath.LastIndexOf('\\')+1);
                string fileExt = fileName.Replace(".gz","");
                fileExt = fileExt.Substring(fileExt.LastIndexOf('.'));

                using (FileStream destination = new FileStream(destinationDirectory + fileName.Remove(fileName.IndexOf("-part")) + fileExt, FileMode.Append, FileAccess.Write),
                                  source = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (GZipStream decompressionStream = new GZipStream(source,CompressionMode.Decompress))
                    {
                        decompressionStream.CopyTo(destination);
                    }
                }
            }
            Console.WriteLine("The file is assembled successfully.");
        }
        private static void DecompressFile(string file)
        {
            byte[] buffer;
            using (var fileStream = File.OpenRead(file))
            {
                using (var compressedStream = new GZipStream(fileStream, CompressionMode.Decompress))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        try
                        {
                            compressedStream.CopyTo(memoryStream);
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            buffer = new byte[memoryStream.Length];
                            memoryStream.Read(buffer, 0, (int)memoryStream.Length);
                        }
                        catch (Exception e)
                        {
                            throw;
                        }
                    }
                }
            }

            File.Create(file).Close();
            File.WriteAllBytes(file, buffer);
        }
        public bool DecompressDataFile(FileInfo dfi)
        {
            bool result;

            try {
                // Get the stream of the source file.
                using (FileStream inFile = dfi.OpenRead())
                {
                    // Get original file extension, by removing ".gz" from Data.sqlite.gz
                    string curFile  = dfi.FullName;
                    string origName = curFile.Remove(curFile.Length - dfi.Extension.Length);

                    //Create the decompressed file.
                    using (FileStream outFile = File.Create(origName))
                    {
                        using (System.IO.Compression.GZipStream Decompress = new System.IO.Compression.GZipStream(inFile,
                                                                                                                  System.IO.Compression.CompressionMode.Decompress))
                        {
                            byte[] tmp = new byte[4];
                            inFile.Read(tmp, 0, 4);
                            inFile.Seek(0, SeekOrigin.Begin);
                            // Copy the decompression stream into the output file.
                            Decompress.CopyTo(outFile);
                            result = true;
                            Console.WriteLine("Decompressed: {0}", dfi.Name);
                        }
                    }
                }
            } catch (Exception e) {
                Console.WriteLine(String.Format("Exception: {0}\n{1}", e.Message, e.StackTrace));
                result = false;
            }

            return(result);
        }
Ejemplo n.º 25
0
        public void TestUnzip()
        {
            var fs          = File.OpenRead(@".\TestFiles\example.svgz");
            var stream      = new System.IO.Compression.GZipStream(fs, CompressionMode.Decompress);
            var destination = File.OpenWrite(@".\TestFiles\example.svg");

            stream.CopyTo(destination);
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Decompresses the content of a stream. The data stream will be closed
 /// </summary>
 /// <param name="data">Data to decompress</param>
 /// <param name="decompressedData">Stream with the decompressed data</param>        
 public static void Decompress(ref Stream data, out Stream decompressedData)
 {
     decompressedData = new MemoryStream();
     var decompress = new GZipStream(data, CompressionMode.Decompress);
     decompress.CopyTo(decompressedData);
     decompress.Close();
     data.Close();
 }
Ejemplo n.º 27
0
 public static byte[] Decompress(byte[] buffer, int index, int count)
 {
     using (var zipStream = new GZipStream(new MemoryStream(buffer, index, count), CompressionMode.Decompress))
     using (var resultStream = new MemoryStream())
     {
         zipStream.CopyTo(resultStream);
         return resultStream.ToArray();
     }
 }
Ejemplo n.º 28
0
 public static string Decompress(this string value)
 {
     using (var msi = new MemoryStream(Convert.FromBase64String(value)))
     using (var mso = new MemoryStream())
     {
         using (var gs = new GZipStream(msi, CompressionMode.Decompress)) gs.CopyTo(mso);
         return Encoding.GetString(mso.ToArray());
     }
 }
Ejemplo n.º 29
0
 public static void UnGZipFileToFile(string compressedfile, string destinationFilename)
 {
     using (Stream fd = File.Create(destinationFilename))
     using (Stream fs = File.OpenRead(compressedfile))
     using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
     {
         csStream.CopyTo(fd);
     }
 }
 public byte[] DecompressWithGzip(byte[] data)
 {
     using (var compressedStream = new MemoryStream(data))
     using (var zipStream = new GZipStream(compressedStream, CompressionMode.Decompress))
     using (var resultStream = new MemoryStream())
     {
         zipStream.CopyTo(resultStream);
         return resultStream.ToArray();
     }
 }
Ejemplo n.º 31
0
 public static byte[] Decompress(byte[] data)
 {
     using (var inStream = new MemoryStream(data))
     using (var zipStream = new GZipStream(inStream, CompressionMode.Decompress))
     using (var outStream = new MemoryStream())
     {
         zipStream.CopyTo(outStream);
         return outStream.ToArray();
     }
 }
Ejemplo n.º 32
0
    static public byte[] DecompressGzip(byte[] compressed)
    {
        using var decompressStream = new System.IO.Compression.GZipStream(
                  new System.IO.MemoryStream(compressed), System.IO.Compression.CompressionMode.Decompress);

        var decompressedStream = new System.IO.MemoryStream();

        decompressStream.CopyTo(decompressedStream);
        return(decompressedStream.ToArray());
    }
Ejemplo n.º 33
0
 public static byte[] GZipDecompress(byte[] data)
 {
     using (var msIn = new MemoryStream(data))
     using (var unzipper = new GZipStream(msIn, CompressionMode.Decompress))
     using (var msOut = new MemoryStream())
     {
         unzipper.CopyTo(msOut);
         return msOut.ToArray();
     }
 }
Ejemplo n.º 34
0
 public byte[] Decompress(byte[] input)
 {
     using (var inputStream = new MemoryStream(input))
     using (var decompressionStream = new GZipStream(inputStream, CompressionMode.Decompress))
     using (var outputStream = new MemoryStream())
     {
         decompressionStream.CopyTo(outputStream);
         return outputStream.ToArray();
     }
 }
Ejemplo n.º 35
0
        public static Stream UnzipStream(Stream input)
        {
            var ms = new MemoryStream();
            using (var gzip = new GZipStream(input, CompressionMode.Decompress, true))
                gzip.CopyTo(ms);

            ms.Position = 0;

            return ms;
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Decompress data using GZip
        /// </summary>
        /// <param name="dataToDecompress">The stream that hold the data</param>
        /// <returns>Bytes array of decompressed data</returns>
        public static byte[] Decompress(Stream dataToDecompress)
        {
            MemoryStream target = new MemoryStream();

            using (System.IO.Compression.GZipStream decompressionStream = new System.IO.Compression.GZipStream(dataToDecompress,
                                                                                                               System.IO.Compression.CompressionMode.Decompress))
            {
                decompressionStream.CopyTo(target);
            }
            return(target.GetBuffer());
        }
Ejemplo n.º 37
0
        /// <summary>
        /// Decompresses the given data stream from its source ZIP or GZIP format.
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        internal static byte[] Inflate(Stream dataStream, CompressionFormat format)
        {
            byte[] outputBytes = null;

            switch (format)
            {
            case CompressionFormat.Zlib:

                try {
                    try {
                        using (var deflateStream = new ZlibStream(dataStream, MonoGame.Utilities.CompressionMode.Decompress))
                        {
                            using (MemoryStream zipoutStream = new MemoryStream())
                            {
                                deflateStream.CopyTo(zipoutStream);
                                outputBytes = zipoutStream.ToArray();
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        CCLog.Log("Error decompressing image data: " + exc.Message);
                    }
                }
                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
                break;

            case CompressionFormat.Gzip:

                try
                {
                    #if !WINDOWS_PHONE
                    var gzipInputStream = new GZipInputStream(dataStream, System.IO.Compression.CompressionMode.Decompress);
                    #else
                    var gzipInputStream = new GZipInputStream(dataStream);
                    #endif

                    MemoryStream zipoutStream = new MemoryStream();
                    gzipInputStream.CopyTo(zipoutStream);
                    outputBytes = zipoutStream.ToArray();
                }
                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
                break;
            }

            return(outputBytes);
        }
Ejemplo n.º 38
0
 private static byte[] Decompress(byte[] compressedBytes)
 {
     using (MemoryStream input = new MemoryStream(compressedBytes))
         using (MemoryStream output = new MemoryStream())
         {
             using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
             {
                 zip.CopyTo(output);
             }
             return(output.ToArray());
         }
 }
Ejemplo n.º 39
0
 public static string DecompressFileToString(string filename)
 {
     using (MemoryStream ms = new MemoryStream())
         using (var fs = File.Open(filename, FileMode.Open))
             using (var gz = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Decompress))
             {
                 gz.CopyTo(ms);
                 ms.Position = 0;
                 using (StreamReader sr = new StreamReader(ms))
                 {
                     return(sr.ReadToEnd());
                 }
             }
 }
Ejemplo n.º 40
0
        /// <summary>
        /// Unzips a zipped stream to the specified stream
        /// </summary>
        /// <param name="zipStream">The zipped stream to un-zip.</param>
        /// <param name="unZipStream">The stream where the unzipped data will be written to.</param>
        /// <param name="zipStreamPosition">Set the zip stream position.</param>
        public static void Decompress(MemoryStream zipStream, MemoryStream unZipStream, long zipStreamPosition = 0)
        {
            // Set the position.
            zipStream.Position = zipStreamPosition;

            // Create all the streams
            using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(zipStream, CompressionMode.Decompress, true))
            {
                // Decompress the data.
                stream.CopyTo(unZipStream);

                // Cleanup the resources.
                stream.Close();
            }
        }
Ejemplo n.º 41
0
        public void TestGZipStream()
        {
            compressor = new System.IO.Compression.GZipStream(compressed, System.IO.Compression.CompressionMode.Compress, true);
            StartCompression();
            compressor.Write(input.GetBuffer(), 0, inputSize);
            compressor.Close();

            EndCompression();

            var decompressor = new System.IO.Compression.GZipStream(compressed, System.IO.Compression.CompressionMode.Decompress, true);

            decompressor.CopyTo(decompressed);

            AfterDecompression();
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Unzips a zipped file to the specified location
        /// </summary>
        /// <param name="zipFilename">The zipped file to un-zip.</param>
        /// <param name="unZipFilename">The file name where the unzipped file will be written to.</param>
        public static void Decompress(string zipFilename, string unZipFilename)
        {
            // Create all the streams
            using (Stream zipStream = File.OpenRead(zipFilename))
                using (Stream unzipStream = File.Create(unZipFilename))
                    using (System.IO.Compression.GZipStream stream = new System.IO.Compression.GZipStream(zipStream, CompressionMode.Decompress))
                    {
                        // Decompress the data.
                        stream.CopyTo(unzipStream);

                        // Cleanup the resources.
                        stream.Close();
                        zipStream.Close();
                        unzipStream.Close();
                    }
        }
Ejemplo n.º 43
0
 public T ToObject <T>(byte[] bytes, Type[] types = null)
 {
     using (MemoryStream stream = new MemoryStream(bytes))
     {
         using (MemoryStream str = new MemoryStream())
         {
             using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(stream, System.IO.Compression.CompressionMode.Decompress))
             {
                 gzip.CopyTo(str);
             }
             return(Newtonsoft.Json.JsonConvert.DeserializeObject <T>(System.Text.Encoding.UTF8.GetString(str.GetBuffer()), new JsonSerializerSettings()
             {
                 TypeNameHandling = TypeNameHandling.All
             }));
         }
     }
 }
Ejemplo n.º 44
0
        public static byte[] Decompress(byte[] file)
        {
            using (EndianBinaryReader r = new EndianBinaryReader(new MemoryStream(file), Endianness.Little))
            {
                uint splitSize  = r.ReadUInt32();
                uint entryCount = r.ReadUInt32();
                uint uncompSize = r.ReadUInt32();

                uint[] splits = r.ReadUInt32s((int)entryCount);
                byte[] output = new byte[uncompSize];

                r.SeekBegin((r.Position + 0x7F) & ~0x7F); // Align

                using (EndianBinaryWriter w = new EndianBinaryWriter(new MemoryStream(output), Endianness.Little))
                {
                    for (int i = 0; i < entryCount; i++)
                    {
                        uint cur_comp = r.ReadUInt32();
                        if (i == entryCount - 1)
                        {
                            if (cur_comp != splits[i] - 4)
                            {
                                w.Write(splits[i]);
                            }
                            else
                            {
                                using (System.IO.Compression.GZipStream deflate = new System.IO.Compression.GZipStream(new MemoryStream(r.ReadBytes((int)cur_comp)), System.IO.Compression.CompressionMode.Decompress))
                                    deflate.CopyTo(w.BaseStream);
                            }
                        }
                        else
                        {
                            if (cur_comp == splits[i] - 4)
                            {
                                using (System.IO.Compression.GZipStream deflate = new System.IO.Compression.GZipStream(new MemoryStream(r.ReadBytes((int)cur_comp)), System.IO.Compression.CompressionMode.Decompress))
                                    deflate.CopyTo(w.BaseStream);
                            }
                        }

                        r.SeekBegin(r.Position + 0x7F & ~0x7F); // Align
                    }
                }
                return(output);
            }
        }
Ejemplo n.º 45
0
        private void ReadConfig()
        {
            MemoryStream ms = new MemoryStream();

            byte[]     SerializeByte    = ms.ToArray();
            FileStream fs               = new FileStream(@".\config.bin", FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
            GZipStream compressedStream = new System.IO.Compression.GZipStream(fs, CompressionMode.Decompress, true);

            compressedStream.CopyTo(ms);
            ms.Position = 0;
            BinaryFormatter binFormat = new BinaryFormatter();

            if (ms.Length != 0)
            {
                config = (Config)binFormat.Deserialize(ms);
            }
            fs.Close();
            ms.Close();
            compressedStream.Close();
        }
Ejemplo n.º 46
0
        /// <summary>
        /// Decompresses the given data stream from its source ZIP or GZIP format.
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        internal static byte[] Inflate(Stream dataStream)
        {
            byte[] outputBytes = null;
            try
            {
                using (var deflateStream = new ZlibStream(dataStream, MonoGame.Utilities.CompressionMode.Decompress))
                {
                    using (MemoryStream zipoutStream = new MemoryStream())
                    {
                        deflateStream.CopyTo(zipoutStream);
                        outputBytes = zipoutStream.ToArray();
                    }
                }
            }
            catch
            {
                try
                {
                    dataStream.Seek(0, SeekOrigin.Begin);
                    #if !WINDOWS_PHONE
                    var gzipInputStream = new GZipInputStream(dataStream, System.IO.Compression.CompressionMode.Decompress);
                    #else
                    var gzipInputStream = new GZipInputStream(dataStream);
                    #endif

                    MemoryStream zipoutStream = new MemoryStream();
                    gzipInputStream.CopyTo(zipoutStream);
                    outputBytes = zipoutStream.ToArray();
                }
                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
            }


            return(outputBytes);
        }
Ejemplo n.º 47
0
        public static System.IO.Stream UnzipStream(System.IO.Stream input, bool zippedStream = true, String contentEncoding = null, String fileName = null)
        {
            System.IO.Stream tempStream = null;

            if (contentEncoding == null)
            {
                contentEncoding = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.ContentEncoding];
            }

            if (String.IsNullOrEmpty(contentEncoding) || !zippedStream)
            {
                if (!String.IsNullOrEmpty(fileName))
                {
                    return(System.IO.File.OpenRead(fileName));
                }
                else
                {
                    return(input);
                }
            }
            else
            {
                switch (contentEncoding.ToLower())
                {
                case "gzip":
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        tempStream = System.IO.File.OpenRead(fileName);
                    }

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(tempStream != null ? tempStream : input, System.IO.Compression.CompressionMode.Decompress, true))
                    {
                        gzip.CopyTo(ms);
                    }
                    ms.Position = 0;

                    return(ms);

                case "deflate":
                    String tempFileName = null;

                    if (String.IsNullOrEmpty(fileName))
                    {
                        tempFileName = Path.Combine(System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString());
                        using (FileStream fs = System.IO.File.OpenWrite(tempFileName))
                        {
                            input.CopyTo(fs);
                            fs.Flush();
                        }
                    }

                    try
                    {
                        using (ZipArchive a = ZipFile.OpenRead(String.IsNullOrEmpty(fileName) ? tempFileName : fileName))
                        {
                            ZipArchiveEntry entry = a.Entries[0];
                            return(entry.Open());
                        }
                    }
                    finally
                    {
                        if (!String.IsNullOrEmpty(tempFileName))
                        {
                            System.IO.File.Delete(tempFileName);
                        }
                    }

                default:
                    throw new Exception("Unsupported content type");
                }
            }
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Decompresses the given data stream from its source ZIP or GZIP format.
        /// </summary>
        /// <param name="dataBytes"></param>
        /// <returns></returns>
        internal static byte[] Inflate(Stream dataStream, CompressionFormat format)
        {
            byte[] outputBytes = null;

            switch (format)
            {
            case CompressionFormat.Zlib:

                try
                {
                    var zipInputStream = new ZipInputStream(dataStream);

                    if (zipInputStream.CanDecompressEntry)
                    {
                        MemoryStream zipoutStream = new MemoryStream();
                        zipInputStream.CopyTo(zipoutStream);
                        outputBytes = zipoutStream.ToArray();
                    }
                    else
                    {
                        dataStream.Seek(0, SeekOrigin.Begin);
                        var inZInputStream = new ZInputStream(dataStream);

                        var outMemoryStream = new MemoryStream();
                        outputBytes = new byte[inZInputStream.BaseStream.Length];

                        while (true)
                        {
                            int bytesRead = inZInputStream.Read(outputBytes, 0, outputBytes.Length);
                            if (bytesRead == 0)
                            {
                                break;
                            }
                            outMemoryStream.Write(outputBytes, 0, bytesRead);
                        }
                    }
                }
                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
                break;

            case CompressionFormat.Gzip:

                try
                {
                    #if !WINDOWS_PHONE
                    var gzipInputStream = new GZipInputStream(dataStream, CompressionMode.Decompress);
                    #else
                    var gzipInputStream = new GZipInputStream(dataStream);
                                        #endif

                    MemoryStream zipoutStream = new MemoryStream();
                    gzipInputStream.CopyTo(zipoutStream);
                    outputBytes = zipoutStream.ToArray();
                } catch (Exception exc) {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
                break;
            }

            return(outputBytes);
        }
Ejemplo n.º 49
0
        public void UploadDataInternal(Common.Solution solution, Stream messageBody, bool checkExisting, bool zippedStream = true, String contentEncoding = null, String fileName = null, Action <int> progressCallback = null, int progressStep = 0)
        {
            System.IO.Stream tempStream = null;

            if (contentEncoding == null && zippedStream)
            {
                contentEncoding = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.ContentEncoding];
            }

            if (String.IsNullOrEmpty(contentEncoding) || !zippedStream)
            {
                if (!String.IsNullOrEmpty(fileName))
                {
                    tempStream = System.IO.File.OpenRead(fileName);
                }
                new DataUploader2(progressCallback, progressStep).UploadData(solution, tempStream != null ? tempStream : messageBody, checkExisting);
            }
            else
            {
                switch (contentEncoding.ToLower())
                {
                case "gzip":
                    if (!String.IsNullOrEmpty(fileName))
                    {
                        tempStream = System.IO.File.OpenRead(fileName);
                    }

                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    using (System.IO.Compression.GZipStream gzip = new System.IO.Compression.GZipStream(tempStream != null ? tempStream : messageBody, System.IO.Compression.CompressionMode.Decompress, true))
                    {
                        gzip.CopyTo(ms);
                    }
                    ms.Position = 0;

                    new DataUploader2(progressCallback, progressStep).UploadData(solution, ms, checkExisting);

                    break;

                case "deflate":
                    String tempFileName = null;

                    if (String.IsNullOrEmpty(fileName))
                    {
                        tempFileName = Path.Combine(System.IO.Path.GetTempPath(), System.Guid.NewGuid().ToString());
                        using (FileStream fs = System.IO.File.OpenWrite(tempFileName))
                        {
                            messageBody.CopyTo(fs);
                            fs.Flush();
                        }
                    }

                    try
                    {
                        using (ZipArchive a = ZipFile.OpenRead(String.IsNullOrEmpty(fileName) ? tempFileName : fileName))
                        {
                            ZipArchiveEntry entry = a.Entries[0];
                            using (System.IO.Stream s = entry.Open())
                            {
                                new DataUploader2(progressCallback, progressStep).UploadData(solution, s, checkExisting);
                            }
                        }
                    }
                    finally
                    {
                        if (!String.IsNullOrEmpty(tempFileName))
                        {
                            System.IO.File.Delete(tempFileName);
                        }
                    }

                    break;

                default:
                    throw new Exception("Unsupported content type");
                }
            }

            if (tempStream != null)
            {
                tempStream.Dispose();
            }
        }