コード例 #1
1
        private byte[] GetBytesFromString(string value)
        {
            var bytes = Encoding.UTF8.GetBytes(value);
            var outputMemStream = new MemoryStream();
            if (bytes.Length > 7950)
            {
                using (var memStream = new MemoryStream(bytes, false))
                {
                    using (outputMemStream)
                    {
                        memStream.Seek(0, SeekOrigin.Begin);
                        using (var zip = new GZipStream(outputMemStream, CompressionLevel.Fastest))
                        {
                            memStream.CopyTo(zip);

                        }
                    }
                }
                return outputMemStream.ToArray();
            }
            else
            {
                return bytes;
            }
        }
コード例 #2
0
ファイル: GzipUtils.cs プロジェクト: longshenwudu/TNet4
        /// <summary>
        /// 解压数据
        /// </summary>
        /// <param name="aSourceStream"></param>
        /// <returns></returns>
        public static byte[] DeCompress(Stream aSourceStream)
        {
            byte[]     vUnZipByte = null;
            GZipStream vUnZipStream;

            using (MemoryStream vMemory = new MemoryStream())
            {
                vUnZipStream = new System.IO.Compression.GZipStream(aSourceStream, CompressionMode.Decompress);
                try
                {
                    byte[] vTempByte = new byte[1024];
                    int    vRedLen   = 0;
                    do
                    {
                        vRedLen = vUnZipStream.Read(vTempByte, 0, vTempByte.Length);
                        vMemory.Write(vTempByte, 0, vRedLen);
                    }while (vRedLen > 0);
                    vUnZipStream.Close();
                }
                finally
                {
                    vUnZipStream.Dispose();
                }
                vUnZipByte = vMemory.ToArray();
            }
            return(vUnZipByte);
        }
コード例 #3
0
        /// <summary> Base64 Zip解压 为 byte[] </summary>
        public static byte[] ZipBase64ToBytes(string xml)
        {
            //base64解码
            System.Text.UTF8Encoding encoder    = new System.Text.UTF8Encoding();
            System.Text.Decoder      utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(xml);
            int    charCount     = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);

            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string decoded = new string(decoded_char);

            //解压缩
            byte[] compressBeforeByte = Convert.FromBase64String(decoded);
            byte[] buffer             = new byte[0x1000];

            using (MemoryStream ms = new MemoryStream(compressBeforeByte))
                using (var zip = new IO.Compression.GZipStream(ms, IO.Compression.CompressionMode.Decompress, true))
                    using (MemoryStream msreader = new MemoryStream())
                    {
                        int reader = 0;
                        while ((reader = zip.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            msreader.Write(buffer, 0, reader);
                        }
                        msreader.Position = 0;
                        buffer            = msreader.ToArray();
                    }

            byte[] compressAfterByte = buffer;
            return(compressAfterByte);
        }
コード例 #4
0
ファイル: OceanModel.cs プロジェクト: pitiplash78/Lib-SPOTL
        /// <summary>
        /// Reads a compressed ocean model.
        /// </summary>
        /// <param name="modelPaths">File path of the ocean model to be read.</param>
        /// <returns>The OceanModel class containing all information about a ocean model.</returns>
        public static OceanModel readTidalModel(string modelPaths)
        {
            OceanModel oceanModel = new OceanModel();

            FileStream sourceFileStream = File.OpenRead(modelPaths);

            System.IO.Compression.GZipStream decompressingStream = new System.IO.Compression.GZipStream(sourceFileStream, System.IO.Compression.CompressionMode.Decompress);

            using (var re = new StreamReader(decompressingStream))
            {
                string dsym = re.ReadLine().Trim();
                string tmp  = re.ReadLine();
                int[]  icte = new int[6];
                for (int i = 0; i < icte.Length; i++)
                {
                    icte[i] = Convert.ToInt32(tmp.Substring(i * 3, 3));
                }
                tmp = re.ReadLine();
                double tlat = double.Parse(tmp.Substring(0, 8), Constants.NumberFormatEN) +
                              double.Parse(tmp.Substring(8, 8), Constants.NumberFormatEN) / 1000d;
                tmp = re.ReadLine();
                double blat = double.Parse(tmp.Substring(0, 8), Constants.NumberFormatEN) +
                              double.Parse(tmp.Substring(8, 8), Constants.NumberFormatEN) / 1000d;
                tmp = re.ReadLine();
                double elong = double.Parse(tmp.Substring(0, 8), Constants.NumberFormatEN) +
                               double.Parse(tmp.Substring(8, 8), Constants.NumberFormatEN) / 1000d;
                tmp = re.ReadLine();
                double wlong = double.Parse(tmp.Substring(0, 8), Constants.NumberFormatEN) +
                               double.Parse(tmp.Substring(8, 8), Constants.NumberFormatEN) / 1000d;
                tmp = re.ReadLine();
                int    latc  = int.Parse(tmp.Substring(0, 8));
                int    longc = int.Parse(tmp.Substring(8, 8));
                string mdnam = re.ReadLine().Trim();
                int[]  ir1   = new int[latc * longc];
                int    j     = 0;
                while (j < ir1.Length)
                {
                    tmp = re.ReadLine();
                    string[] parts = tmp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int k = 0; k < parts.Length; k++)
                    {
                        ir1[j++] = int.Parse(parts[k]);
                    }
                }

                int[] im1 = new int[latc * longc];
                j = 0;
                while (j < im1.Length)
                {
                    tmp = re.ReadLine();
                    string[] parts = tmp.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int k = 0; k < parts.Length; k++)
                    {
                        im1[j++] = int.Parse(parts[k]);
                    }
                }
                oceanModel = new OceanModel(dsym, icte, tlat, blat, elong, wlong, latc, longc, mdnam, ir1, im1);
            }
            return(oceanModel);
        }
コード例 #5
0
 private async Task <Stream> DecompressToStream(Stream dataStr)
 {
     using (var gzipStream = new System.IO.Compression.GZipStream(dataStr, CompressionMode.Decompress))
     {
         return(await gzipStream.CopyStreamAsync());
     }
 }
コード例 #6
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))
                {
                    outputBytes = StreamToByteArray(deflateStream);
                }
            }
            catch
            {
                try
                {
                    dataStream.Seek(0, SeekOrigin.Begin);
                    #if !WINDOWS_PHONE
                    using (var gzipInputStream = new GZipInputStream(dataStream, System.IO.Compression.CompressionMode.Decompress))
                    #else
                    using (var gzipInputStream = new GZipInputStream(dataStream))
                    #endif
                    {
                        outputBytes = StreamToByteArray(gzipInputStream);
                    }
                }
                catch (Exception exc)
                {
                    CCLog.Log("Error decompressing image data: " + exc.Message);
                }
            }


            return(outputBytes);
        }
コード例 #7
0
        public override byte[] Load( Stream stream, Game game, out int width, out int height, out int length )
        {
            byte[] map = null;
            width = 0;
            height = 0;
            length = 0;
            LocalPlayer p = game.LocalPlayer;
            p.SpawnPoint = Vector3.Zero;

            using( GZipStream gs = new GZipStream( stream, CompressionMode.Decompress ) ) {
                reader = new BinaryReader( gs );
                ClassDescription obj = ReadData();
                for( int i = 0; i < obj.Fields.Length; i++ ) {
                    FieldDescription field = obj.Fields[i];
                    if( field.FieldName == "width" )
                        width = (int)field.Value;
                    else if( field.FieldName == "height" )
                        length = (int)field.Value;
                    else if( field.FieldName == "depth" )
                        height = (int)field.Value;
                    else if( field.FieldName == "blocks" )
                        map = (byte[])field.Value;
                    else if( field.FieldName == "xSpawn" )
                        p.SpawnPoint.X = (int)field.Value;
                    else if( field.FieldName == "ySpawn" )
                        p.SpawnPoint.Y = (int)field.Value;
                    else if( field.FieldName == "zSpawn" )
                        p.SpawnPoint.Z = (int)field.Value;
                }
            }
            return map;
        }
コード例 #8
0
ファイル: MapJTE.cs プロジェクト: fragmer/fCraft
 public Map LoadHeader( string fileName ) {
     using( FileStream mapStream = File.OpenRead( fileName ) ) {
         using( GZipStream gs = new GZipStream( mapStream, CompressionMode.Decompress ) ) {
             return LoadHeaderInternal( gs );
         }
     }
 }
コード例 #9
0
        public static string GetHTMLByHttpRequest(string url, string proxy, int timeout = 5000)
        {
            HttpWebRequest wr = (HttpWebRequest)HttpWebRequest.Create(url);

            if (string.IsNullOrWhiteSpace(proxy))
            {
                wr.Proxy = null;
            }
            else
            {
                wr.Proxy = new WebProxy(proxy);
            }
            wr.Timeout = timeout;
            HttpWebResponse wrp     = (HttpWebResponse)wr.GetResponse();
            var             charset = wrp.CharacterSet;
            string          c       = string.Empty;
            Stream          st      = wrp.GetResponseStream();

            if (wrp.ContentEncoding.ToLower().Contains("gzip"))
            {
                st = new System.IO.Compression.GZipStream(st, System.IO.Compression.CompressionMode.Decompress);
            }
            using (var sr = new StreamReader(st
                                             , Encoding.GetEncoding(charset)))
            {
                c = sr.ReadToEnd();
            }
            return(c);
        }
コード例 #10
0
ファイル: ZipHelper.cs プロジェクト: franknew/SOAFramework
 public static byte[] ZipToByte(string value, Encoding encode, bool useGzip = false)
 {
     byte[] byteArray = encode.GetBytes(value);
     byte[] data      = null;
     //Prepare for compress
     System.IO.MemoryStream ms = new System.IO.MemoryStream();
     if (useGzip)
     {
         System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
         //Compress
         sw.Write(byteArray, 0, byteArray.Length);
         //Close, DO NOT FLUSH cause bytes will go missing...
         sw.Close();
         sw.Dispose();
     }
     else
     {
         ms.Write(byteArray, 0, byteArray.Length);
     }
     data = ms.ToArray();
     //Transform byte[] zip data to string
     ms.Close();
     ms.Dispose();
     return(data);
 }
コード例 #11
0
        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);
        }
コード例 #12
0
ファイル: NetUtil.cs プロジェクト: jonbws/strengthreport
        public static string GZipUtf8ResultToString(DownloadDataCompletedEventArgs e)
        {
            if(e.Cancelled || (e.Error != null) || (e.Result == null))
                return null;

            MemoryStream msZipped = new MemoryStream(e.Result);
            GZipStream gz = new GZipStream(msZipped, CompressionMode.Decompress);
            BinaryReader br = new BinaryReader(gz);
            MemoryStream msUTF8 = new MemoryStream();

            while(true)
            {
                byte[] pb = null;

                try { pb = br.ReadBytes(4096); }
                catch(Exception) { }

                if((pb == null) || (pb.Length == 0)) break;

                msUTF8.Write(pb, 0, pb.Length);
            }

            br.Close();
            gz.Close();
            msZipped.Close();

            return Encoding.UTF8.GetString(msUTF8.ToArray());
        }
コード例 #13
0
        public static byte[] Compress(byte[] data, bool useGZipCompression = true)

        {
            System.IO.Compression.CompressionLevel compressionLevel = System.IO.Compression.CompressionLevel.Fastest;

            using (MemoryStream memoryStream = new MemoryStream())

            {
                if (useGZipCompression)

                {
                    using (System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream,

                                                                                                              compressionLevel, true))

                    {
                        gZipStream.Write(data, 0, data.Length);
                    }
                }

                else

                {
                    using (System.IO.Compression.GZipStream gZipStream = new System.IO.Compression.GZipStream(memoryStream,

                                                                                                              compressionLevel, true))

                    {
                        gZipStream.Write(data, 0, data.Length);
                    }
                }

                return(memoryStream.ToArray());
            }
        }
コード例 #14
0
        private void Save(PageContent content, int id, string suffix)
        {
            EnsureDirectoryExists(this._settings.StoragePath);

            string imageFileName = this.BuildFileName(id, suffix, ".jpg");

            if (!File.Exists(imageFileName))
            {
                EnsureDirectoryExists(Path.GetDirectoryName(imageFileName));
                content.Screenshot.Save(imageFileName, ImageFormat.Jpeg);
            }

            string contentFileName = this.BuildFileName(id, suffix, ".json.gz");

            if (!File.Exists(contentFileName))
            {
                // compress and  save
                //using (var writer = new StreamWriter(contentFileName))
                //{
                //	new JsonSerializer().Serialize(writer, content);
                //}
                EnsureDirectoryExists(Path.GetDirectoryName(contentFileName));
                using (var writer = new StreamWriter(contentFileName).BaseStream)
                    using (var _gzstream = new System.IO.Compression.GZipStream(writer, CompressionLevel.Optimal))
                        using (var streamWriter = new StreamWriter(_gzstream))
                            using (var jsonWriter = new JsonTextWriter(streamWriter))
                            {
                                new JsonSerializer().Serialize(jsonWriter, content);
                            }
            }
        }
コード例 #15
0
        static void Main(string[] args)
        {
            GZipStream gzOut = new GZipStream(File.Create(@"C:\Writing1mb.zip"), CompressionMode.Compress);
            DeflateStream dfOut = new DeflateStream(File.Create(@"C:\Writing1mb2.zip"), CompressionMode.Compress);
            TextWriter tw = new StreamWriter(gzOut);
            TextWriter tw2 = new StreamWriter(dfOut);

            try
            {
                for(int i = 0; i < 1000000; i++)
                {
                    tw.WriteLine("Writing until more than 1mb to ZIP it!");
                    tw2.WriteLine("Writing until more than 1mb to ZIP it!");
                }
            }
            catch(Exception)
            {

                throw;
            }
            finally
            {
                tw.Close();
                gzOut.Close();
                tw2.Close();
                dfOut.Close();
            }

        }
コード例 #16
0
ファイル: Gzip.cs プロジェクト: rbwestmoreland/AL-Redis
        public static byte[] Decompress(byte[] bytes)
        {
            using (var gzipStream = new GZipStream(new MemoryStream(bytes), CompressionMode.Decompress))
            {
                const int size = 4096;
                var buffer = new byte[size];

                using (var stream = new MemoryStream())
                {
                    int count;

                    do
                    {
                        count = gzipStream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            stream.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);

                    return stream.ToArray();
                }
            }
        }
コード例 #17
0
        public void TestMethod1()
        {
            using (var sourceStream = File.OpenRead(@"C:\Data\mongo-dump-2016-01-14.tar.gz"))
                using (var unZipStream = new System.IO.Compression.GZipStream(sourceStream, System.IO.Compression.CompressionMode.Decompress))
                    using (var tarStream = new TarStream(unZipStream))
                    {
                        while (tarStream.NextFile())
                        {
                            var taredFileExtention = Path.GetExtension(tarStream.CurrentFilename);

                            if (tarStream.CurrentFilename == "dump/github/org_members.bson") //taredFileExtention == ".bson")
                            {
                                using (var output = File.Create("org_members.bson"))
                                {
                                    Byte[] outputBytes = new byte[8196];
                                    while (tarStream.Read(outputBytes, 0, 8196) > 0)
                                    {
                                        output.Write(outputBytes, 0, outputBytes.Length);
                                    }
                                }
                            }
                        }
                        ;
                    }
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: Mascavidrio/KeePassDPG
        /// <summary>
        /// Write the specified list of words to a compressed file.
        /// </summary>
        /// <param name="wordList"></param>
        private static void WriteCompressedFile(WordList wordList)
        {
            string filePath = Path.Combine(Path.GetDirectoryName(_sourceFile), string.Format("words{0}.gz", wordList.WordLength));

            using (FileStream compressedFile = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                using (GZipStream compressionStream = new GZipStream(compressedFile, CompressionMode.Compress))
                {
                    try
                    {
                        // Output new file
                        string data = String.Join(" ", wordList.ToArray());
                        byte[] bytes = new byte[data.Length * sizeof(char)];
                        Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);

                        using (MemoryStream stream = new MemoryStream(bytes))
                        {
                            stream.CopyTo(compressionStream);

                            Console.WriteLine("{0} created.", Path.GetFileName(filePath));
                            Console.WriteLine();
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        Console.WriteLine(ex.StackTrace);
                        Console.WriteLine();
                    }
                }
            }
        }
コード例 #19
0
ファイル: Compressor.cs プロジェクト: eByte23/Smidge
        public static async Task<Stream> CompressAsync(CompressionType type, Stream original)
        {            
            using (var ms = new MemoryStream())
            {
                Stream compressedStream = null;

                if (type == CompressionType.deflate)
                {
                    compressedStream = new DeflateStream(ms, CompressionMode.Compress);
                }
                else if (type == CompressionType.gzip)
                {
                    compressedStream = new GZipStream(ms, CompressionMode.Compress);
                }

                if (type != CompressionType.none)
                {
                    using (compressedStream)
                    {
                        await original.CopyToAsync(compressedStream);
                    }

                    //NOTE: If we just try to return the ms instance, it will simply not work
                    // a new stream needs to be returned that contains the compressed bytes.
                    // I've tried every combo and this appears to be the only thing that works.

                    byte[] output = ms.ToArray();
                    return new MemoryStream(ms.ToArray());
                }

                //not compressed
                return original;
            }
        }
コード例 #20
0
        public static string decompress(this FileInfo fi, string targetFile)
        {
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                //Create the decompressed file.
                using (FileStream outFile = File.Create(targetFile))
                {
                    using (var decompress = new GZipStream(inFile, CompressionMode.Decompress))
                    {
                        //Copy the decompression stream into the output file.
                        var buffer = new byte[4096];
                        int numRead;
                        while ((numRead = decompress.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            outFile.Write(buffer, 0, numRead);
                        }

                        "Decompressed: {0}".info(fi.Name);

                    }
                }
            }
            return targetFile;
        }
コード例 #21
0
ファイル: NBTReader.cs プロジェクト: RevolutionSmythe/c-raft
        /// <summary>
        /// Creates a new NBT reader with a specified memory stream.
        /// </summary>
        /// <param name="memIn">The memory stream in which the NBT is located.</param>
        /// <param name="version">The compression version of the NBT, choose 1 for GZip and 2 for ZLib.</param>
        public NBTReader(MemoryStream memIn, int version)
        {
            /*  Due to a file specification change on how an application reads a NBT file
             *  (Minecraft maps are now compressed via a z-lib deflate stream), this method
             *  provides backwards support for the old GZip decompression stream (in case for raw NBT files
             *  and old Minecraft chunk files).
             */

            // meaning the NBT is compressed via a GZip stream
            if (version == 1)
            {
                // decompress the stream
                GZipStream gStream = new GZipStream(memIn, CompressionMode.Decompress);

                // route the stream to a binary reader
                _bRead = new BinaryReader(memIn);
            }
            // meaning the NBT is compressed via a z-lib stream
            else if (version == 2)
            {
                // a known bug when deflating a zlib stream...
                // for more info, go here: http://www.chiramattel.com/george/blog/2007/09/09/deflatestream-block-length-does-not-match.html
                memIn.ReadByte();
                memIn.ReadByte();

                // deflate the stream
                DeflateStream dStream = new DeflateStream(memIn, CompressionMode.Decompress);

                // route the stream to a binary reader
                _bRead = new BinaryReader(dStream);
            }
        }
コード例 #22
0
ファイル: Compression.cs プロジェクト: DrPrickett/GIT
        public string CompressString(string text)
        {
            try
            {
                byte[]       buffer = System.Text.Encoding.Unicode.GetBytes(text);
                MemoryStream ms     = new MemoryStream();
                using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress, true))
                {
                    zip.Write(buffer, 0, buffer.Length);
                }

                ms.Position = 0;
                MemoryStream outStream = new MemoryStream();

                byte[] compressed = new byte[ms.Length];
                ms.Read(compressed, 0, compressed.Length);

                byte[] gzBuffer = new byte[compressed.Length + 4];

                System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
                System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
                return(Convert.ToBase64String(gzBuffer));
            }
            catch (Exception err)
            {
                return(err.Message.ToString());
            }
        }
コード例 #23
0
ファイル: GZIP.cs プロジェクト: heksesang/sharpotify
        public static byte[] Inflate(byte[] bytes)
        {
            MemoryStream ms = new MemoryStream(bytes);
            MemoryStream output = new MemoryStream();
            GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress);

            byte[] buffer = new byte[BUFFER_SIZE];
            try
            {
                while (gzip.CanRead)
                {
                    int bytesRead = gzip.Read(buffer, 0, buffer.Length);
                    if (bytesRead <= 0)
                        break;
                    output.Write(buffer, 0, bytesRead);
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                gzip.Close();
                ms = null;
            }

            return output.ToArray();
        }
コード例 #24
0
ファイル: Compression.cs プロジェクト: DrPrickett/GIT
        public string DeCompressString(string compressedText)
        {
            try
            {
                byte[] gzBuffer = Convert.FromBase64String(compressedText);
                using (MemoryStream ms = new MemoryStream())
                {
                    int msgLength = BitConverter.ToInt32(gzBuffer, 0);
                    ms.Write(gzBuffer, 4, gzBuffer.Length - 4);

                    byte[] buffer = new byte[msgLength];

                    ms.Position = 0;
                    using (System.IO.Compression.GZipStream zip = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress))
                    {
                        zip.Read(buffer, 0, buffer.Length);
                    }

                    return(System.Text.Encoding.Unicode.GetString(buffer, 0, buffer.Length));
                }
            }
            catch (Exception err)
            {
                return(err.Message.ToString());
            }
        }
コード例 #25
0
        /// <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);
                    }
                }
            }
        }
コード例 #26
0
        public static void Compress(string FileToCompress, string CompressedFile)
        {
            byte[] buffer = new byte[1024 * 1024]; // 1MB

            using (System.IO.FileStream sourceFile = System.IO.File.OpenRead(FileToCompress))
            {
                using (System.IO.FileStream destinationFile = System.IO.File.Create(CompressedFile))
                {
                    using (System.IO.Compression.GZipStream output = new System.IO.Compression.GZipStream(destinationFile,
                                                                                                          System.IO.Compression.CompressionMode.Compress))
                    {
                        int bytesRead = 0;
                        while (bytesRead < sourceFile.Length)
                        {
                            int ReadLength = sourceFile.Read(buffer, 0, buffer.Length);
                            output.Write(buffer, 0, ReadLength);
                            output.Flush();
                            bytesRead += ReadLength;
                        } // Whend

                        destinationFile.Flush();
                    } // End Using System.IO.Compression.GZipStream output

                    destinationFile.Close();
                } // End Using System.IO.FileStream destinationFile

                // Close the files.
                sourceFile.Close();
            } // End Using System.IO.FileStream sourceFile
        }     // End Sub CompressFile
コード例 #27
0
        public ManagedBitmap(string fileName)
        {
            try
            {
                byte[] buffer = new byte[1024];
                MemoryStream fd = new MemoryStream();
                Stream fs = File.OpenRead(fileName);
                using (Stream csStream = new GZipStream(fs, CompressionMode.Decompress))
                {
                    int nRead;
                    while ((nRead = csStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        fd.Write(buffer, 0, nRead);
                    }
                    csStream.Flush();
                    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;
            }
        }
コード例 #28
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);
                }
            }
        }
コード例 #29
0
ファイル: ImageSearch.cs プロジェクト: ksasao/Gochiusearch
        public async Task<ImageInfo[]> LoadFromDbAsync(string dbFileName)
        {
            var file = await FileSystem.Current.GetFileFromPathAsync(dbFileName).ConfigureAwait(false);
            if (file == null)
                throw new FileNotFoundException();
            using (var fs = await file.OpenAsync(FileAccess.Read).ConfigureAwait(false))
            using (var gz = new GZipStream(fs, CompressionMode.Decompress))
            using (var br = new BinaryReader(gz))
            {
                long count = br.ReadInt32();
                _info = new ImageInfo[count];

                for (var i = 0; i < count; i++)
                {
                    var hash = br.ReadUInt64();
                    var titleId = br.ReadUInt16();
                    var episodeId = br.ReadUInt16();
                    var frame = br.ReadUInt32();
                    _info[i] = new ImageInfo
                    {
                        Hash = hash,
                        TitleId = titleId,
                        EpisodeId = episodeId,
                        Frame = frame
                    };
                }
            }
            return _info;
        }
コード例 #30
0
        public void Run()
        {
            string folder = @"c:\temp";
            string uncompressedFilePath = Path.Combine(folder, "uncompressed.dat");
            string compressedFilePath = Path.Combine(folder, "compressed.gz");
            byte[] dataToCompress = Enumerable.Repeat((byte) 'a', 1024*1024).ToArray();

            using (FileStream uncompressedFileStream = File.Create(uncompressedFilePath))
            {
                uncompressedFileStream.Write(dataToCompress, 0, dataToCompress.Length);
            }
            using (FileStream compressedFileStream = File.Create(compressedFilePath))
            {
                using (var compressionStream = new GZipStream(
                    compressedFileStream, CompressionMode.Compress))
                {
                    compressionStream.Write(dataToCompress, 0, dataToCompress.Length);
                }
            }

            var uncompressedFile = new FileInfo(uncompressedFilePath);
            var compressedFile = new FileInfo(compressedFilePath);

            Console.WriteLine(uncompressedFile.Length);
            Console.WriteLine(compressedFile.Length);
        }
コード例 #31
0
ファイル: CompressionUtils.cs プロジェクト: jemc771/MongoREST
 public static string Compress(string text)
 {
   try
   {
     byte[] buffer = Encoding.UTF8.GetBytes(text);
     using (MemoryStream ms = new MemoryStream())
     {
       using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
       {
         zip.Write(buffer, 0, buffer.Length);
       }
       ms.Position = 0;
       using (MemoryStream outStream = new MemoryStream())
       {
         byte[] compressed = new byte[ms.Length];
         ms.Read(compressed, 0, compressed.Length);
         byte[] gzBuffer = new byte[compressed.Length + 4];
         System.Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
         System.Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
         string final = Convert.ToBase64String(gzBuffer);
         return final;
       }
     }
   }
   catch (Exception ex)
   {
     return ex.Message;
   }
 }
コード例 #32
0
		private void DownloadStream (Stream str, string compressed_mime)
		{
			// access must be verified before calling this method (no verification is done here)
			if (compressed_mime == MimeTypes.GZ) {
				string AcceptEncoding = Request.Headers["Accept-Encoding"];
				if (!string.IsNullOrEmpty (AcceptEncoding) && AcceptEncoding.Contains ("gzip")) {
					Response.AppendHeader ("Content-Encoding", "gzip");
				} else {
					str = new GZipStream (str, CompressionMode.Decompress);
				}
			}
			
			try {
				if (!(str is GZipStream))
					Response.AppendHeader ("Content-Length", str.Length.ToString ());
			} catch (NotSupportedException)  {
				// GZipStreams don't usually know their length, just ignore
			}

			byte [] buffer = new byte [1024];
			int read;
			int total = 0;

			read = str.Read (buffer, 0, buffer.Length);
			total += read;
			while (read > 0) {
				Response.OutputStream.Write (buffer, 0, read);
				read = str.Read (buffer, 0, buffer.Length);
				total += read;
				Response.Flush ();
			}
		}
コード例 #33
0
        /// <summary>
        /// Http Get
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="encode">编码</param>
        /// <param name="contentType">类型</param>
        /// <param name="nvc">头</param>
        /// <param name="isGzip">是否Gzip压缩</param>
        /// <returns>返回请求结果,如果请求失败则返回空字符串</returns>
        public static string HttpGet(string url, string encode, string contentType, NameValueCollection nvc = null, bool isGzip = false)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                    throw new Exception("Url Is Null");

                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
                    ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";

                if (!string.IsNullOrWhiteSpace(contentType))
                    request.ContentType = contentType;

                if (nvc != null && nvc.Count > 0)
                    request.Headers.Add(nvc);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream myResponseStream = response.GetResponseStream();
                if (isGzip) myResponseStream = new GZipStream(myResponseStream, CompressionMode.Decompress);
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding(encode));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();

                return retString;
            }
            catch (Exception ex)
            {
                return "";
            }
        }
コード例 #34
0
ファイル: BinaryOcrDb.cs プロジェクト: m1croN/subtitleedit
 public void Save()
 {
     using (Stream gz = new GZipStream(File.OpenWrite(FileName), CompressionMode.Compress))
     {
         foreach (var bob in CompareImages)
         {
             if (bob.ExpandCount > 0)
                 System.Windows.Forms.MessageBox.Show("Ups, expand image in CompareImages!");
             bob.Save(gz);
         }
         foreach (var bob in CompareImagesExpanded)
         {
             if (bob.ExpandCount == 0)
                 System.Windows.Forms.MessageBox.Show("Ups, not expanded image in CompareImagesExpanded!");
             bob.Save(gz);
             if (bob.ExpandedList.Count != bob.ExpandCount -1)
             {
                 throw new Exception("BinaryOcrDb.Save: Expanded image should have " + (bob.ExpandCount - 1) + " sub images");
             }
             foreach (var expandedBob in bob.ExpandedList)
             {
                 if (expandedBob.Text != null)
                     throw new Exception("BinaryOcrDb.Save: sub image should have null text");
                 expandedBob.Save(gz);
             }
         }
     }
 }
コード例 #35
0
    public override TagCompound Load(string fileName, NbtOptions options)
    {
      TagCompound tag;
      BinaryTagReader reader;

      if (string.IsNullOrEmpty(fileName))
        throw new ArgumentNullException("fileName");

      if (!File.Exists(fileName))
        throw new FileNotFoundException("Cannot find source file.", fileName);

      //Check if gzipped stream
      try
      {
        using (FileStream input = File.OpenRead(fileName))
        {
          using (GZipStream gzipStream = new GZipStream(input, CompressionMode.Decompress))
          {
            reader = new BinaryTagReader(gzipStream, NbtOptions.Header);
            tag = (TagCompound)reader.Read();
          }
        }
      }
      catch (Exception)
      {
        tag = null;
      }

      if (tag != null)
        return tag;

      //Try Deflate stream
      try
      {
        using (FileStream input = File.OpenRead(fileName))
        {
          using (DeflateStream deflateStream = new DeflateStream(input, CompressionMode.Decompress))
          {
            reader = new BinaryTagReader(deflateStream, NbtOptions.Header);
            tag = (TagCompound)reader.Read();
          }
        }
      }
      catch (Exception)
      {
        tag = null;
      }

      if (tag != null)
        return tag;

      //Assume uncompressed stream
      using (FileStream input = File.OpenRead(fileName))
      {
        reader = new BinaryTagReader(input, NbtOptions.Header);
        tag = (TagCompound)reader.Read();
      }

      return tag;
    }
コード例 #36
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);
        }
コード例 #37
0
ファイル: ZipHelper.cs プロジェクト: vanloc0301/mychongchong
 public static byte[] GZCompress(byte[] source)
 {
     byte[] buffer;
     if ((source == null) || (source.Length == 0))
     {
         throw new ArgumentNullException("source");
     }
     try
     {
         using (MemoryStream stream = new MemoryStream())
         {
             using (GZipStream stream2 = new GZipStream(stream, CompressionMode.Compress, true))
             {
                 Console.WriteLine("Compression");
                 stream2.Write(source, 0, source.Length);
                 stream2.Flush();
                 stream2.Close();
                 Console.WriteLine("Original size: {0}, Compressed size: {1}", source.Length, stream.Length);
                 stream.Position = 0L;
                 buffer = stream.ToArray();
             }
         }
     }
     catch (Exception exception)
     {
         LoggingService.Error("GZip压缩时出错:", exception);
         buffer = source;
     }
     return buffer;
 }
コード例 #38
0
ファイル: CompressedContent.cs プロジェクト: heinnge/ravendb
        protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            using (var uncloseableStream = new UndisposableStream(stream))
            using (var bufferedStream = new BufferedStream(uncloseableStream))
            {
                Stream compressedStream = null;

                if (encodingType == "gzip")
                {
                    compressedStream = new GZipStream(bufferedStream, CompressionMode.Compress, leaveOpen: true);
                }
                else if (encodingType == "deflate")
                {
                    compressedStream = new DeflateStream(bufferedStream, CompressionMode.Compress, leaveOpen: true);
                }
                else throw new InvalidOperationException("This shouldn't happen, ever.");

                await originalContent.CopyToAsync(compressedStream);

                if (compressedStream != null)
                {
                    compressedStream.Dispose();
                }
            }
        }
コード例 #39
0
ファイル: GetHtmlCode.cs プロジェクト: reckcn/CSharp
        //public static string GetHtmlByCom(string url)
        //{
        //    XMLHTTP xmlhttp = new XMLHTTPClass();
        //    xmlhttp.open("get", url, false, null, null);
        //    xmlhttp.send("");
        //    while (xmlhttp.readyState != 4) Thread.Sleep(1);
        //    return xmlhttp.responseText;
        //}   

        /// <summary>
        /// 用Get方法返回网页源代码
        /// </summary>
        /// <param name="url">标识Internet资源的uri</param>
        /// <param name="encoding">网页编码</param>
        /// <returns>网页源代码</returns>
        public static string GetByget(string url, string encoding)
        {
            Stream sr = null;
            StreamReader sReader = null;
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "Get";
                request.Timeout = 30000;

                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                if (response.ContentEncoding.ToLower() == "gzip")//如果使用了GZip则先解压
                {
                    sr = new GZipStream(response.GetResponseStream(), CompressionMode.Decompress);
                }
                else
                {
                    sr = response.GetResponseStream();
                }
                sReader = new StreamReader(sr, System.Text.Encoding.GetEncoding(encoding));
                return sReader.ReadToEnd();
            }
            catch
            {
                return null;
            }
            finally
            {
                if (sReader != null)
                    sReader.Close();
                if (sr != null)
                    sr.Close();
            }
        }
コード例 #40
0
        public static string compress(this FileInfo fi, string targetFile)
        {
            targetFile.deleteIfExists();
            // Get the stream of the source file.
            using (FileStream inFile = fi.OpenRead())
            {
                // Prevent compressing hidden and already compressed files.
                if ((File.GetAttributes(fi.FullName) & FileAttributes.Hidden)
                        != FileAttributes.Hidden & fi.Extension != ".gz")
                {
                    // Create the compressed file.
                    using (FileStream outFile = File.Create(targetFile))
                    {
                        using (var compress = new GZipStream(outFile, CompressionMode.Compress))
                        {
                            // Copy the source file into the compression stream.
                            var buffer = new byte[4096];
                            int numRead;
                            while ((numRead = inFile.Read(buffer, 0, buffer.Length)) != 0)
                                compress.Write(buffer, 0, numRead);

                            "Compressed {0} from {1} to {2} bytes.".info(fi.Name, fi.Length.str(), outFile.Length.str());
                        }
                    }
                }
            }
            if (targetFile.fileExists())
                return targetFile;
            return null;
        }
コード例 #41
0
        /// <summary>
        /// Decompresses an array of bytes.
        /// </summary>
        /// <param name="bytes">The array of bytes to decompress.</param>
        /// <returns>The decompressed array of bytes.</returns>
        public static byte[] Decompress(this byte[] bytes)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(bytes, 0, bytes.Length);
                stream.Position = 0;

                using (GZipStream compressedStream = new GZipStream(stream, CompressionMode.Decompress, true))
                {
                    using (MemoryStream output = new MemoryStream())
                    {
                        byte[] buffer = new byte[32*1024];
                        int count = compressedStream.Read(buffer, 0, buffer.Length);
                        while (count > 0)
                        {
                            output.Write(buffer, 0, count);
                            count = compressedStream.Read(buffer, 0, buffer.Length);
                        }

                        compressedStream.Close();
                        return output.ToArray();
                    }
                }
            }
        }
コード例 #42
0
ファイル: Gzip.cs プロジェクト: YuleSouza/Loja
        public static byte[] Decompress(byte[] gzip)
        {
            if (gzip == null)
            {
                return null;
            }
             const int size = 4096;
               
            // Create a GZIP stream with decompression mode.
            // ... Then create a buffer and write into while reading from the GZIP stream.
            using (var stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
            {

               
                var buffer = new byte[size];
                using (var memory = new MemoryStream())
                {
                    var count = 0;
                    do
                    {
                        count = stream.Read(buffer, 0, size);
                        if (count > 0)
                        {
                            memory.Write(buffer, 0, count);
                        }
                    }
                    while (count > 0);
                    return memory.ToArray();
                }
            }
        }
コード例 #43
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");
            }
コード例 #44
0
ファイル: GZip.cs プロジェクト: DesselBane/DarkSeng
        /// <summary>
        /// Compresses the file with the GZip algorithm
        /// </summary>
        /// <param name="sourcePath">Path to the file which will be compressed</param>
        /// <param name="destinationPath">Path to the directory where the compressed file will be copied to</param>
        public static void Compress(string sourcePath, string destinationPath)
        {
            try
            {
                FileInfo fileToCompress = new FileInfo(sourcePath);

                using (FileStream originalFileStream = fileToCompress.OpenRead())
                {
                    if ((File.GetAttributes(fileToCompress.FullName) &
                        FileAttributes.Hidden) != FileAttributes.Hidden & fileToCompress.Extension != ".gz")
                    {
                        using (FileStream compressedFileStream = File.Create(destinationPath + "\\" + fileToCompress.Name + ".gz"))
                        {
                            using (GZipStream compressionStream = new GZipStream(compressedFileStream,
                                CompressionMode.Compress))
                            {
                                originalFileStream.CopyTo(compressionStream);

                            }
                        }

                        FileInfo info = new FileInfo(destinationPath + "\\" + fileToCompress.Name + ".gz");
                    }
                }
            }
            catch
            {
            }
        }
コード例 #45
0
ファイル: GZip.cs プロジェクト: albfernandez/dalle
 protected override void _Unir(string fichero, string dirDest)
 {
     if (!File.Exists (fichero))
     {
         return;
     }
     FileInfo fi = new FileInfo (fichero);
     string destino = dirDest + Path.DirectorySeparatorChar + fi.Name.Substring (0, fi.Name.LastIndexOf ('.'));
     long datosTotales = fi.Length;
     FileStream input = File.OpenRead (fichero);
     datosTotales = GetUncompressedSize (input);
     GZipStream gzipInput = new GZipStream (input, CompressionMode.Decompress);
     Stream fos = UtilidadesFicheros.CreateWriter (destino);
     byte[] buffer = new byte[Consts.BUFFER_LENGTH];
     int leidos = 0;
     long transferidos=0;
     OnProgress (0, datosTotales);
     while ((leidos = gzipInput.Read (buffer, 0, buffer.Length)) > 0)
     {
         fos.Write (buffer, 0, leidos);
         transferidos += leidos;
         OnProgress (transferidos, datosTotales);
     }
     gzipInput.Close ();
     fos.Close ();
 }
コード例 #46
0
ファイル: Compressor.cs プロジェクト: hultqvist/scatter
        static void CompressFile(string path)
        {
            DateTime fileDate = File.GetLastWriteTime(path);

            //Minify uncompressed file
            if (path.EndsWith(".js"))
            {
                string original = File.ReadAllText(path, Encoding.UTF8);
                if (string.IsNullOrEmpty(original))
                    return;
                string compressed = jc.Compress(original);
                File.WriteAllText(path, compressed, Encoding.UTF8);
                File.SetLastWriteTime(path, fileDate);
            }
            if (path.EndsWith(".css"))
            {
                string original = File.ReadAllText(path, Encoding.UTF8);
                if (string.IsNullOrEmpty(original))
                    return;
                string compressed = cc.Compress(original);
                File.WriteAllText(path, compressed, Encoding.UTF8);
                File.SetLastWriteTime(path, fileDate);
            }

            //Compress
            using (GZipStream gz = new GZipStream(new FileStream(path + ".gz", FileMode.Create), CompressionMode.Compress))
            {
                byte[] buffer = File.ReadAllBytes(path);
                gz.Write(buffer, 0, buffer.Length);
            }

            File.SetLastWriteTime(path + ".gz", fileDate);
        }
コード例 #47
0
        /// <summary />
        internal static byte[] ZipBytes(this byte[] byteArray, bool fast = true)
        {
            if (byteArray == null)
            {
                return(null);
            }
            try
            {
                //Prepare for compress
                using (var ms = new System.IO.MemoryStream())
                {
                    var level = System.IO.Compression.CompressionLevel.Fastest;
                    if (!fast)
                    {
                        level = System.IO.Compression.CompressionLevel.Optimal;
                    }
                    using (var sw = new System.IO.Compression.GZipStream(ms, level))
                    {
                        //Compress
                        sw.Write(byteArray, 0, byteArray.Length);
                        sw.Close();

                        //Transform byte[] zip data to string
                        return(ms.ToArray());
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
コード例 #48
0
        public static string Zip(string value)
        {
            //Transform string into byte[]
            byte[] byteArray = new byte[value.Length];
            int    indexBA   = 0;

            char[] charArray = value.ToCharArray();
            foreach (char item in charArray)
            {
                byteArray[indexBA++] = (byte)item;
            }

            //Prepare for compress
            System.IO.MemoryStream           ms = new System.IO.MemoryStream();
            System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms,
                                                                                       System.IO.Compression.CompressionMode.Compress);

            //Compress
            sw.Write(byteArray, 0, byteArray.Length);
            //Close, DO NOT FLUSH cause bytes will go missing...
            sw.Close();

            //Transform byte[] zip data to string
            byteArray = ms.ToArray();
            System.Text.StringBuilder sB = new System.Text.StringBuilder(byteArray.Length);
            foreach (byte item in byteArray)
            {
                sB.Append((char)item);
            }
            ms.Close();
            sw.Dispose();
            ms.Dispose();
            return(sB.ToString());
        }
コード例 #49
0
    public static string Decompress(string s)
    {
        if (string.IsNullOrEmpty(s))
        {
            return("");
        }
        if (GameState.UseNewSaveCompression)
        {
            return(Decompress2(s));
        }
        try
        {
            Span <byte> buffer = new Span <byte>(new byte[s.Length]);
            if (Convert.TryFromBase64String(s, buffer, out int b) == false)
            {
                if (Convert.TryFromBase64String(s.PadRight(s.Length / 4 * 4 + (s.Length % 4 == 0 ? 0 : 4), '='), new Span <byte>(new byte[s.Length]), out int pad))
                {
                    Console.WriteLine("String Length:" + s.Length);
                    Console.WriteLine("Bytes parsed:" + pad);
                    Console.WriteLine("End padding:" + s.Substring(s.Length - 10));
                    using (var source = new MemoryStream(Convert.FromBase64String(s)))
                    {
                        byte[] len = new byte[4];
                        source.Read(len, 0, 4);
                        var l = BitConverter.ToInt32(len, 0);
                        using (var decompressionStream = new System.IO.Compression.GZipStream(source, System.IO.Compression.CompressionMode.Decompress))
                        {
                            var result = new byte[l];
                            decompressionStream.Read(result, 0, l);
                            return(Encoding.UTF8.GetString(result));
                        }
                    }
                }
                else
                {
                    Console.WriteLine("Padding failed.");
                    Console.WriteLine("String Length:" + s.Length);
                    Console.WriteLine("Bytes parsed:" + b);
                    Console.WriteLine("End padding:" + s.Substring(s.Length - 10));
                }
            }
            using (var source = new MemoryStream(Convert.FromBase64String(s)))
            {
                byte[] len = new byte[4];
                source.Read(len, 0, 4);
                var l = BitConverter.ToInt32(len, 0);
                using (var decompressionStream = new System.IO.Compression.GZipStream(source, System.IO.Compression.CompressionMode.Decompress))
                {
                    var result = new byte[l];
                    decompressionStream.Read(result, 0, l);
                    return(Encoding.UTF8.GetString(result));
                }
            }
        }

        catch {
            return(Decompress2(s));
        }
    }
コード例 #50
0
ファイル: WebUtil.cs プロジェクト: Jinkela-N/AcHelper
        /// <summary>
        /// 已登录持有cookie进行post
        /// </summary>
        /// <param name="postUrl"></param>
        /// <param name="referUrl"></param>
        /// <param name="data"></param>
        /// <param name="cookiec"></param>
        /// <returns></returns>
        public string PostData(string postUrl, string referUrl, string data, CookieContainer cookiec)
        {
            //data = System.Web.HttpUtility.UrlEncode(data);
            string result = "";

            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
                myHttpWebRequest.AllowAutoRedirect = true;
                myHttpWebRequest.KeepAlive         = true;
                myHttpWebRequest.Accept            = "*/*";
                myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                myHttpWebRequest.CookieContainer = cookiec;
                myHttpWebRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
                myHttpWebRequest.ContentType     = "application/x-www-form-urlencoded; charset=UTF-8";
                myHttpWebRequest.Referer         = referUrl;
                myHttpWebRequest.Method          = "POST";
                myHttpWebRequest.Timeout         = 10000;
                myHttpWebRequest.ContentLength   = data.Length;
                Stream postStream = myHttpWebRequest.GetRequestStream();
                byte[] postData   = Encoding.UTF8.GetBytes(data);
                postStream.Write(postData, 0, postData.Length);
                postStream.Dispose();
                HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
                response.Cookies = cookiec.GetCookies(myHttpWebRequest.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                StreamReader sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);
                if (response.ContentLength > 1)
                {
                    result = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    result = sb.ToString();
                }
                sr.Close();
                response.Close();
                string s = result;
                return(s);
            }
            catch { }
            return("");
        }
コード例 #51
0
ファイル: SvgzTest.cs プロジェクト: zhuowp-fork/SvgToXaml
        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);
        }
コード例 #52
0
ファイル: WebUtil.cs プロジェクト: Jinkela-N/AcHelper
        /// <summary>
        /// 功能描述:在PostLogin成功登录后记录下Headers中的cookie,然后获取此网站上其他页面的内容
        /// </summary>
        /// <param name="strURL">获取网站的某页面的地址</param>
        /// <param name="strReferer">引用的地址</param>
        /// <returns>返回页面内容</returns>
        public string GetPage(string strURL, string strReferer, CookieContainer cookiec)
        {
            string strResult = "";

            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strURL);
                myHttpWebRequest.AllowAutoRedirect = true;
                myHttpWebRequest.KeepAlive         = false;
                myHttpWebRequest.Accept            = "*/*";
                myHttpWebRequest.Referer           = strReferer;
                myHttpWebRequest.Headers.Add("Accept-Encoding", "gzip, deflate");
                myHttpWebRequest.CookieContainer = cookiec;
                myHttpWebRequest.UserAgent       = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 2.0.50727)";
                myHttpWebRequest.ContentType     = "application/json;charset=UTF-8";
                myHttpWebRequest.Method          = "GET";
                myHttpWebRequest.Timeout         = 10000;
                HttpWebResponse        response = null;
                System.IO.StreamReader sr       = null;
                response         = (HttpWebResponse)myHttpWebRequest.GetResponse();
                response.Cookies = cookiec.GetCookies(myHttpWebRequest.RequestUri);
                Stream streamReceive;
                string gzip = response.ContentEncoding;
                if (string.IsNullOrEmpty(gzip) || gzip.ToLower() != "gzip")
                {
                    streamReceive = response.GetResponseStream();
                }
                else
                {
                    streamReceive = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
                }
                sr = new System.IO.StreamReader(streamReceive, Encoding.UTF8);
                if (response.ContentLength > 1)
                {
                    strResult = sr.ReadToEnd();
                }
                else
                {
                    char[]        buffer = new char[256];
                    int           count  = 0;
                    StringBuilder sb     = new StringBuilder();
                    while ((count = sr.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        sb.Append(new string(buffer));
                    }
                    strResult = sb.ToString();
                }
                sr.Close();
                response.Close();
            }
            catch (Exception)
            {
                // throw;
            }
            return(strResult);
        }
コード例 #53
0
 /// <summary>
 /// 压缩数据组
 /// </summary>
 /// <param name="source"></param>
 /// <returns></returns>
 public static byte[] Compress(this byte[] source)
 {
     using (var ms = new System.IO.MemoryStream())
         using (var gzip = new System.IO.Compression.GZipStream(ms, CompressionMode.Compress))
         {
             gzip.Write(source);
             gzip.Close();
             return(ms.ToArray());
         }
 }
コード例 #54
0
ファイル: Utilities.cs プロジェクト: mndambuki/Emby
        /// <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());
        }
コード例 #55
0
ファイル: Repository.cs プロジェクト: kozandser/MyDB
        private static void CompressStringToFile(this string s, string filename)
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(s);
            using (MemoryStream ms = new MemoryStream(byteArray))
                using (var fs = File.Create(filename))

                    using (var gz = new System.IO.Compression.GZipStream(fs, System.IO.Compression.CompressionMode.Compress))
                    {
                        ms.WriteTo(gz);
                    }
        }
コード例 #56
0
ファイル: ZipUtils.cs プロジェクト: swindy/CocosSharp
        /// <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);
        }
コード例 #57
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());
         }
 }
コード例 #58
0
        public static Byte[] GZipJsonString(string jsonBody)
        {
            string inputStr = jsonBody;

            byte[] inputBytes = Encoding.UTF8.GetBytes(inputStr);
            using (var outputStream = new MemoryStream())
            {
                using (var gZipStream = new System.IO.Compression.GZipStream(outputStream, System.IO.Compression.CompressionMode.Compress))
                    gZipStream.Write(inputBytes, 0, inputBytes.Length);
                return(inputBytes);
            }
        }
コード例 #59
0
    public static void Main(string[] args)
    {
        Console.WriteLine("Start");
        int           virtualDeviceId            = 154;
        int           virtualDeviceIdHighestTemp = 166;
        int           virtualDeviceIdLowestTemp  = 167;
        List <string> placeIds = new List <string> {
            "283", "340"
        };
        string countyId = "01";

        LogToHomeseer("Start WarmWater script");
        string cachebash = DateTime.Now.ToString("yyyyMMddHHmmss");

        System.Net.WebRequest webRequest = System.Net.WebRequest.Create(@"http://localhost:1234/?cachebash=" + cachebash);
        webRequest.Headers.Set(HttpRequestHeader.CacheControl, "max-age=0, no-cache, no-store");
        System.IO.Stream       content;
        System.Net.WebResponse response = webRequest.GetResponse();
        if (((System.Net.HttpWebResponse)response).ContentEncoding == "gzip")
        {
            content = new System.IO.Compression.GZipStream(response.GetResponseStream(), System.IO.Compression.CompressionMode.Decompress);
        }
        else
        {
            content = response.GetResponseStream();
        }
        System.IO.StreamReader reader = new System.IO.StreamReader(content);
        string strContent             = reader.ReadToEnd();

        if (strContent.Length > 0)
        {
            Console.WriteLine(strContent);
            var formattedData = SplitContent(strContent);
            //splitt content Probabillity=0.972492337226868;Rotation=-87;FileChangedDate=2018-01-05 08:13:44;DeliveryDate=2018-01-05 17:39:40
            var splitBySemiColon = strContent.Split(';');

            foreach (var info in splitBySemiColon)
            {
                Console.WriteLine(info);
            }

            //var rot=new ReceivedData(splitBySemiColon[1]);

            Console.WriteLine("----");
            Console.WriteLine(formattedData.Probabillity);

            UpdateHomeSeerDevices(formattedData, args);
        }
        LogToHomeseer("Done");

        // return 0;
    }
コード例 #60
0
ファイル: CodeBuilder.cs プロジェクト: wwwK/EntityDB
 static byte[] GZip(byte[] byteArray)
 {
     using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
     {
         System.IO.Compression.GZipStream sw = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Compress);
         //Compress
         sw.Write(byteArray, 0, byteArray.Length);
         //Close, DO NOT FLUSH cause bytes will go missing...
         sw.Close();
         //Transform byte[] zip data to string
         return(ms.ToArray());
     }
 }