【问题标题】:how can i download and extract single file from http using sharpziplib in c#?如何使用 c# 中的 sharpziplib 从 http 下载和提取单个文件?
【发布时间】:2017-03-29 21:05:14
【问题描述】:

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

【问题讨论】:

  • 您需要下载完整的文件,将其保存为本地文件或存储在 MemoryStream 中

标签: c# http sharpziplib


【解决方案1】:

您可以在没有外部依赖的情况下做到这一点。添加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);
            }
        }
    }
}

您可以根据需要将 HttpClient 替换为 WebClient 或 HttpRequest。

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

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

【讨论】:

  • 感谢您的回答,但如果我想从这个存储库中提取和下载单个文件?这就是我的意思
  • 您无法在不下载整个 zip 文件的情况下提取单个文件。无需遍历所有 zip 文件条目,只需选择您要查找的条目(例如:使用 linq)。我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 1970-01-01
  • 2016-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多