如何在c#中使用sharpziplib从http下载并提取单个文件?

时间:2017-03-29 21:05:15

标签: c# http sharpziplib

有人知道我怎么能这样做?我尝试重新制作这段代码,但它不起作用。 Unpack a zip using ZipInputStream (eg for Unseekable input streams)

1 个答案:

答案 0 :(得分:0)

你可以在没有外部依赖的情况下完成。添加System.IO.Compression.dll并像这样使用

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);
            }
        }
    }
}

如果需要,可以通过WebClient或HttpRequest替换HttpClient。

如果您只想提取一个文件,请将foreach (var entry in ar.Entries)替换为:

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