【问题标题】:'Could not find a part of the path' error when extracting zip in .net core在 .net 核心中提取 zip 时出现“找不到路径的一部分”错误
【发布时间】:2020-02-06 16:50:26
【问题描述】:

我正在尝试将 zip 文件解压缩到某个位置,但出现以下错误:

System.IO.DirectoryNotFoundException: '找不到一部分 路径 'D:\test\Server\project\test.edb\Article.eod'。'

我正在以管理员权限运行 VS Studio。源文件存在,并且在调试时相对路径似乎正确。实际的 zip 文件包含文件夹和文件夹中的文件,我不确定这是否是问题的原因。

string zipPath = @".\..\..\assets\project.zip";
string projectPath = @".\..\..\project";
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
    foreach(ZipArchiveEntry entry in archive.Entries)
    {
        String fullPath = Path.Combine(projectPath, entry.FullName);
        if (String.IsNullOrEmpty(entry.Name))
        {
            Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
        }
        entry.ExtractToFile(fullPath, true);
    }
}

【问题讨论】:

  • 按 F10 并调试您的代码。仅当 entry.Name 为空时才创建目录,这很可能永远不会发生。
  • @CodeCaster 但是逻辑不正确吗?如果当前条目是文件夹名称而不是文件,则会创建一个目录,然后将其中的文件递归提取到该目录。
  • 我不知道这个API,你确定zip文件中的目录是由一个条目表示的吗? AFAIK,它不是,所以你的 if() 永远不会被执行。再次,单步执行您的代码以找出答案。调用Directory.CreateDirectory() 也没有什么坏处,如果它已经存在,该方法本身不会做任何事情。

标签: .net asp.net-core .net-core path


【解决方案1】:

entry.ExtractToFile 将 zip 存档中的条目提取到文件中,目录会出错。

如果你想提取一个 zip 文件,你可以使用

ZipFile.ExtractToDirectory(zipPath, projectPath);

参考https://docs.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchive?view=netcore-3.0

【讨论】:

  • ZipFile.ExtractToDirectory(zipPath, projectPath) 如果文件已存在,则会失败。 ExtractToFile(fullPath, true) 让您覆盖
猜你喜欢
  • 2022-12-05
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2020-03-02
相关资源
最近更新 更多