题
我需要定期下载、提取并保存内容 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
其他提示
您可以使用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 压缩和解压缩文件。
示例用法可以在此找到 博客文章:
using ICSharpCode.SharpZipLib.Zip;
FastZip fz = new FastZip();
fz.ExtractZip(zipFile, targetDirectory,"");
这 压缩流 类可能就是你想要的。
不隶属于 StackOverflow