[ACCEPTED]-How do you download and extract a gzipped file with C#?-gzip
To compress:
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);
}
}
To Decompress:
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);
}
}
}
}
Taken from a post 4 I wrote last year that shows how to decompress 3 a gzip file using C# and the built-in GZipStream 2 class. http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx
As for downloading it, you can use 1 the standard WebRequest or WebClient classes in .NET.
You can use WebClient in System.Net to download:
WebClient Client = new WebClient ();
Client.DownloadFile("http://data.dot.state.mn.us/dds/det_sample.xml.gz", " C:\mygzipfile.gz");
then 2 use #ziplib to extract
Edit: or GZipStream... forgot 1 about that one
Try the SharpZipLib, a C# based library for compressing 2 and uncompressing files using gzip/zip.
Sample 1 usage can be found on this blog post:
using ICSharpCode.SharpZipLib.Zip;
FastZip fz = new FastZip();
fz.ExtractZip(zipFile, targetDirectory,"");
Just use the HttpWebRequest class in the System.Net namespace 4 to request the file and download it. Then 3 use GZipStream class in the System.IO.Compression 2 namespace to extract the contents to the 1 location you specify. They provide examples.
You can use the HttpContext
object to download a csv.gz 2 file
Convert you DataTable
into string using 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();
You 1 can extract this downloaded file using 7Zip
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.