代码之家  ›  专栏  ›  技术社区  ›  John Sheehan

如何使用C#下载和解压缩gzip压缩的文件?

  •  23
  • John Sheehan  · 技术社区  · 17 年前

    我需要定期下载、提取和保存 http://data.dot.state.mn.us/dds/det_sample.xml.gz 到磁盘。有人用C#下载gzip压缩文件的经验吗?

    6 回复  |  直到 17 年前
        1
  •  28
  •   Manoj Sharma    8 年前

    要压缩,请执行以下操作:

    using (FileStream fStream = new FileStream(@"C:\test.docx.gzip", 
    FileMode.Create, FileAccess.Write)) {
        using (GZipStream zipStream = new GZipStream(fStream, 
        CompressionMode.Compress)) {
            byte[] inputfile = File.ReadAllBytes(@"c:\test.docx");
            zipStream.Write(inputfile, 0, inputfile.Length);
        }
    }
    

    要解压缩,请执行以下操作:

    using (FileStream fInStream = new FileStream(@"c:\test.docx.gz", 
    FileMode.Open, FileAccess.Read)) {
        using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress)) {   
            using (FileStream fOutStream = new FileStream(@"c:\test1.docx", 
            FileMode.Create, FileAccess.Write)) {
                byte[] tempBytes = new byte[4096];
                int i;
                while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0) {
                    fOutStream.Write(tempBytes, 0, i);
                }
            }
        }
    }
    

    摘自我去年写的一篇文章,展示了如何使用C#和内置的GZipStream类解压缩gzip文件。 http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx

    至于下载,您可以使用标准 WebRequest WebClient 班级在。网。

        2
  •  7
  •   Adam Haile    17 年前

    您可以在系统中使用WebClient。网络下载:

    WebClient Client = new WebClient ();
    Client.DownloadFile("http://data.dot.state.mn.us/dds/det_sample.xml.gz", " C:\mygzipfile.gz");
    

    然后使用 #ziplib 提取

    编辑:或GZipStream。..忘了那个

        3
  •  4
  •   Dale Ragan    17 年前

    试试 SharpZipLib ,一个基于C#的库,用于使用gzip/zip压缩和解压缩文件。

    示例用法可以在此处找到 blog post :

    using ICSharpCode.SharpZipLib.Zip;
    
    FastZip fz = new FastZip();       
    fz.ExtractZip(zipFile, targetDirectory,"");
    
        4
  •  4
  •   Marek Grzenkowicz    14 年前

    只需使用 HttpWebRequest 系统中的类。Net命名空间请求文件并下载。然后使用 GZipStream 系统中的类。IO.Production命名空间,用于将内容提取到您指定的位置。他们提供了例子。

        5
  •  2
  •   Patrick    17 年前

    这个 GZipStream 上课可能是你想要的。