【发布时间】:2010-09-06 05:17:36
【问题描述】:
我需要定期下载、提取http://data.dot.state.mn.us/dds/det_sample.xml.gz 的内容并将其保存到磁盘。任何人都有使用 C# 下载 gzip 文件的经验?
【问题讨论】:
我需要定期下载、提取http://data.dot.state.mn.us/dds/det_sample.xml.gz 的内容并将其保存到磁盘。任何人都有使用 C# 下载 gzip 文件的经验?
【问题讨论】:
压缩:
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 中的标准WebRequest 或WebClient 类。
【讨论】:
您可以使用 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...忘了那个
【讨论】:
试试SharpZipLib,这是一个基于 C# 的库,用于使用 gzip/zip 压缩和解压缩文件。
可以在blog post上找到示例用法:
using ICSharpCode.SharpZipLib.Zip;
FastZip fz = new FastZip();
fz.ExtractZip(zipFile, targetDirectory,"");
【讨论】:
只需使用 System.Net 命名空间中的HttpWebRequest 类来请求文件并下载它。然后使用 System.IO.Compression 命名空间中的GZipStream 类将内容提取到您指定的位置。他们提供了例子。
【讨论】:
GZipStream 类可能是您想要的。
【讨论】:
您可以使用HttpContext 对象下载 csv.gz 文件
使用StringBuilder (inputString) 将您的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 解压这个下载的文件
【讨论】: