gpt4 book ai didi

c# - ZipFile.ExtractToDirectory "Illegal characters in path"

转载 作者:行者123 更新时间:2023-12-02 21:27:00 39 4
gpt4 key购买 nike

我想用 C# (VS2012) 中的 ZipFile 类解压缩文件。即使我直接从 win 资源管理器复制路径,我也会收到此错误:

System.ArgumentException: Illegales Zeichen im Pfad. bei System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional) bei System.IO.Path.GetFileName(String path) bei System.IO.Compression.ZipHelper.EndsWithDirChar(String test) bei System.IO.Compression.ZipArchiveEntry.set_FullName(String value)
bei System.IO.Compression.ZipArchiveEntry..ctor(ZipArchive archive, ZipCentralDirectoryFileHeader cd) bei System.IO.Compression.ZipArchive.ReadCentralDirectory() bei System.IO.Compression.ZipArchive.get_Entries() bei System.IO.Compression.ZipFileExtensions.ExtractToDirectory(ZipArchive source, String destinationDirectoryName) bei System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName, Encoding entryNameEncoding) bei System.IO.Compression.ZipFile.ExtractToDirectory(String sourceArchiveFileName, String destinationDirectoryName) bei WindowsFormsApplication1.MainForm.buttonStartNxtOSEK_Click(Object sender, EventArgs e) in d:\C#\nxtOSEKInstaller\nxtOSEKSetup\WindowsFormsApplication1\Form1.cs:Zeile 192.

代码:

string zipPath = @"D:\C#\nxtOSEKInstaller\nxtOSEKSetup\WindowsFormsApplication1\bin\Debug\res\package.zip";
string extractPath = @"D:\testcyginstall\cygwin";

textBoxProgress.AppendText("Entpacke .... ");
try {
ZipFile.ExtractToDirectory(zipPath, extractPath);
} catch (System.ArgumentException ex) {
textBoxProgress.AppendText("\n" + "Error\n" + ex.ToString());
return;
}

编辑问题已解决:zip 文件中某些带有中文文件名的文件导致了该问题。当异常没有输出有问题的路径名时,这是非常令人沮丧的。

最佳答案

正如您所知,某些字符在 Windows 上无效:

\ / : * ? " < > |

当您的应用程序从不同操作系统接收 zip 时,这会带来很多情况,因为其中一些无效字符在其他操作系统中是有效的。

为了解决此问题,您可以在提取文件名之前对其进行清理:

public void ExtractZipFileToPath(
string zipFilePath,
string ouputPath
)
{
using (var zip = ZipFile.Read(zipFilePath))
{
foreach (var entry in zip.Entries.ToList())
{
entry.FileName = SanitizeFileName(entry.FileName);
entry.Extract(ouputPath);
}
}
}

此处的清理示例 How to remove illegal characters from path and filenames?

关于c# - ZipFile.ExtractToDirectory "Illegal characters in path",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23407717/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com