我需要定期从http://data.dot.state.mn.us/dds/det_sample.xml.gz下载、提取并保存文件内容到硬盘。请问有谁用C#下载过压缩文件的经验?
压缩:
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类。
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压缩和解压文件。
可以在这个博客文章中找到示例用法:
using ICSharpCode.SharpZipLib.Zip;
FastZip fz = new FastZip();
fz.ExtractZip(zipFile, targetDirectory,"");
只需使用 System.Net 命名空间中的 HttpWebRequest 类请求文件并下载。然后使用 System.IO.Compression 命名空间中的 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提取此下载文件