我想用 c# (VS2012) 中的 ZipFile 类解压缩文件。即使我直接从 win explorer 复制路径,我也会收到此错误:
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(字符串值)
在 System.IO.Compression.ZipArchiveEntry..ctor(ZipArchive archive, ZipCentralDirectoryFileHeader cd) 在 System.IO.Compression.ZipArchive.ReadCentralDirectory() 在 System.IO.Compression.ZipArchive.get_Entries() 在 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) beiWindowsFormsApplication1。 .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;
}
Run Code Online (Sandbox Code Playgroud)
编辑 问题已解决: 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
此处的清理示例如何从路径和文件名中删除非法字符?