How do you download and extract a gzipped file wit

2019-03-12 02:43发布

问题:

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#?

回答1:

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.



回答2:

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



回答3:

Try the SharpZipLib, a C# based library for compressing and uncompressing files using gzip/zip.

Sample usage can be found on this blog post:

using ICSharpCode.SharpZipLib.Zip;

FastZip fz = new FastZip();       
fz.ExtractZip(zipFile, targetDirectory,"");


回答4:

Just use the HttpWebRequest class in the System.Net namespace to request the file and download it. Then use GZipStream class in the System.IO.Compression namespace to extract the contents to the location you specify. They provide examples.



回答5:

The GZipStream class might be what you want.



标签: c# .net gzip