http://data.dot.state.mn.us/dds/det_sample.xml.gzのコンテンツを定期的にダウンロードして抽出し、ディスクに保存する必要があります。C# で gzip されたファイルをダウンロードした経験のある人はいますか?
6 に答える
圧縮するには:
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 ...それを忘れていました
gzip/zip を使用してファイルを圧縮および解凍するための C# ベースのライブラリであるSharpZipLibを試してください。
サンプルの使用法は、次のブログ投稿にあります。
using ICSharpCode.SharpZipLib.Zip;
FastZip fz = new FastZip();
fz.ExtractZip(zipFile, targetDirectory,"");
System.Net 名前空間のHttpWebRequestクラスを使用してファイルを要求し、ダウンロードするだけです。次に、System.IO.Compression 名前空間のGZipStreamクラスを使用して、コンテンツを指定した場所に抽出します。それらは例を提供します。
GZipStreamクラスは、あなたが望むものかもしれません。
オブジェクトを使用しHttpContext
て csv.gz ファイルをダウンロードできます
( )DataTable
を使用して文字列に変換しますStringBuilder
inputString
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 を使用して抽出できます。