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

23
6个回答

29

压缩:

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

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


+1 这个链接对我很有帮助,我第一次使用压缩功能。非常好的、有用的、简洁的博客文章。 - J M

7
您可以使用System.Net中的WebClient来下载:
WebClient Client = new WebClient ();
Client.DownloadFile("http://data.dot.state.mn.us/dds/det_sample.xml.gz", " C:\mygzipfile.gz");

然后使用#ziplib进行解压缩。

编辑:或者使用GZipStream...忘记了这个。


5

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

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

using ICSharpCode.SharpZipLib.Zip;

FastZip fz = new FastZip();       
fz.ExtractZip(zipFile, targetDirectory,"");

4

只需使用 System.Net 命名空间中的 HttpWebRequest 类请求文件并下载。然后使用 System.IO.Compression 命名空间中的 GZipStream 类将内容提取到您指定的位置。它们提供了示例。


2

0

您可以使用 HttpContext 对象下载 csv.gz 文件

使用 StringBuilderinputString)将您的 DataTable 转换为字符串

byte[] buffer = Encoding.ASCII.GetBytes(inputString.ToString());
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.csv.gz", fileName));
HttpContext.Current.Response.Filter = new GZipStream(HttpContext.Current.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
using (GZipStream zipStream = new GZipStream(HttpContext.Current.Response.OutputStream, CompressionMode.Compress))
{
    zipStream.Write(buffer, 0, buffer.Length);
}
HttpContext.Current.Response.End();

您可以使用7Zip提取此下载文件


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接