简体   繁体   中英

how can i download and extract single file from http using sharpziplib in c#?

anybody know how could i do that? i tried remake this code but it does not work. Unpack a zip using ZipInputStream (eg for Unseekable input streams)

You can do it without external dependency. Add System.IO.Compression.dll and use it like this

using (var client = new System.Net.Http.HttpClient())
using (var stream = client.GetStreamAsync("https://github.com/frictionlessdata/specs/archive/master.zip").Result)
{
    var basepath = Path.Combine(Path.GetTempPath() + "myzip");
    System.IO.Directory.CreateDirectory(basepath);

    var ar = new System.IO.Compression.ZipArchive(stream, System.IO.Compression.ZipArchiveMode.Read);
    foreach (var entry in ar.Entries)
    {
        var path = Path.Combine(basepath, entry.FullName);

        if (string.IsNullOrEmpty(entry.Name))
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            continue;
        }

        using (var entryStream = entry.Open())
        {
            System.IO.Directory.CreateDirectory(Path.GetDirectoryName(path));
            using (var file = File.Create(path))
            {
                entryStream.CopyTo(file);
            }
        }
    }
}

You can replace HttpClient by WebClient or HttpRequest if you want.

If you want to extract only one file, replace foreach (var entry in ar.Entries) by :

var entry = ar.Entries.FirstOrDefault(e => e.FullName.EndWith("myFile.txt"));
if(entry == null)
    return;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM