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

Joh*_*han 23 .net c# gzip

我需要定期下载,提取并保存http://data.dot.state.mn.us/dds/det_sample.xml.gz的内容到磁盘.任何人都有使用C#下载gzip压缩文件的经验?

Jer*_*ark 28

要压缩:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

要解压缩:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

至于下载它,您可以使用.NET中的标准WebRequestWebClient类.


Ada*_*ile 7

您可以在System.Net中使用WebClient进行下载:

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

然后使用#ziplib进行提取

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


Yaa*_*lis 5

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

用法示例可以在此博客文章中找到:

using ICSharpCode.SharpZipLib.Zip;

FastZip fz = new FastZip();       
fz.ExtractZip(zipFile, targetDirectory,"");
Run Code Online (Sandbox Code Playgroud)