• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Compression.GZipStream类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.Compression.GZipStream的典型用法代码示例。如果您正苦于以下问题:C# GZipStream类的具体用法?C# GZipStream怎么用?C# GZipStream使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



GZipStream类属于System.IO.Compression命名空间,在下文中一共展示了GZipStream类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: Inflate

        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();
        }
开发者ID:heksesang,项目名称:sharpotify,代码行数:28,代码来源:GZIP.cs


示例2: compress

        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;
        }
开发者ID:njmube,项目名称:FluentSharp,代码行数:30,代码来源:GZip_ExtensionMethods.cs


示例3: GetBytesFromString

        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;
            }
        }
开发者ID:ctigeek,项目名称:TestMemcachedVsSqlServer,代码行数:25,代码来源:Program.cs


示例4: LoadFromDbAsync

        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;
        }
开发者ID:ksasao,项目名称:Gochiusearch,代码行数:29,代码来源:ImageSearch.cs


示例5: Decompress

        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();
                }
            }
        }
开发者ID:YuleSouza,项目名称:Loja,代码行数:31,代码来源:Gzip.cs


示例6: Run

        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);
        }
开发者ID:rrsc,项目名称:ProgrammingInCSharp,代码行数:26,代码来源:CompressingDataWithAGZipStream.cs


示例7: Decompress

        /// <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();
                    }
                }
            }
        }
开发者ID:petervyvey,项目名称:membrane,代码行数:30,代码来源:CompressionExtension.cs


示例8: WriteCompressedFile

        /// <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();
                    }
                }
            }
        }
开发者ID:Mascavidrio,项目名称:KeePassDPG,代码行数:36,代码来源:Program.cs


示例9: CompressAsync

        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;
            }
        }
开发者ID:eByte23,项目名称:Smidge,代码行数:34,代码来源:Compressor.cs


示例10: Main

        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();
            }

        }
开发者ID:Rafael-Miceli,项目名称:ProjectStudiesCert70-536,代码行数:29,代码来源:Program.cs


示例11: GZipUtf8ResultToString

        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());
        }
开发者ID:jonbws,项目名称:strengthreport,代码行数:28,代码来源:NetUtil.cs


示例12: Load

    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;
    }
开发者ID:koponk,项目名称:Cyotek.Data.Nbt,代码行数:60,代码来源:BinaryTagReader.cs


示例13: Load

        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;
        }
开发者ID:umby24,项目名称:ClassicalSharp,代码行数:32,代码来源:MapDat.Importer.cs


示例14: Open

        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);
                }
            }
        }
开发者ID:BennyKJohnson,项目名称:Ego-Engine-Modding,代码行数:28,代码来源:PssgFile.cs


示例15: CompressFile

        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);
        }
开发者ID:hultqvist,项目名称:scatter,代码行数:33,代码来源:Compressor.cs


示例16: GZCompress

 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;
 }
开发者ID:vanloc0301,项目名称:mychongchong,代码行数:30,代码来源:ZipHelper.cs


示例17: SerializeToStreamAsync

        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();
                }
            }
        }
开发者ID:heinnge,项目名称:ravendb,代码行数:25,代码来源:CompressedContent.cs


示例18: _Unir

 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 ();
 }
开发者ID:albfernandez,项目名称:dalle,代码行数:26,代码来源:GZip.cs


示例19: GetByget

        //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();
            }
        }
开发者ID:reckcn,项目名称:CSharp,代码行数:49,代码来源:GetHtmlCode.cs


示例20: HttpGet

        /// <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 "";
            }
        }
开发者ID:iZhongCheng,项目名称:Common.Utility,代码行数:43,代码来源:HttpHelper.cs



注:本文中的System.IO.Compression.GZipStream类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Compression.ZipArchive类代码示例发布时间:2022-05-26
下一篇:
C# Compression.DeflateStream类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap