Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you download and extract a gzipped file with C#?

Tags:

I need to periodically download, extract and save the contents of http://data.dot.state.mn.us/dds/det_sample.xml.gz to disk. Anyone have experience downloading gzipped files with C#?

like image 461
John Sheehan Avatar asked Aug 19 '08 20:08

John Sheehan


People also ask

How do I unzip a tarball file?

Simply right-click the item you want to compress, mouseover compress, and choose tar. gz. You can also right-click a tar. gz file, mouseover extract, and select an option to unpack the archive.

What is a GZ file and how do I open it?

A GZ file is an archive file compressed by the standard GNU zip (gzip) compression algorithm. It typically contains a single compressed file but may also store multiple compressed files. gzip is primarily used on Unix operating systems for file compression.


2 Answers

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 I wrote last year that shows how to decompress a gzip file using C# and the built-in GZipStream class. http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx

As for downloading it, you can use the standard WebRequest or WebClient classes in .NET.

like image 142
JeremiahClark Avatar answered Sep 30 '22 11:09

JeremiahClark


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 use #ziplib to extract

Edit: or GZipStream... forgot about that one

like image 24
Adam Haile Avatar answered Sep 30 '22 13:09

Adam Haile