如何处理使用太长/重复的路径解压缩 ZipFile



在Windows中解压缩文件时,我偶尔会遇到路径问题

  1. 对于 Windows 来说太长了(但在创建文件的原始操作系统中没问题(。
  2. 由于不区分大小写而"重复">

使用 DotNetZip,每当读取具有这些问题之一的 zip 文件时,ZipFile.Read(path)调用都会变得废话。 这意味着我什至无法尝试过滤掉它。

using (ZipFile zip = ZipFile.Read(path))
{
    ...
}

处理读取此类文件的最佳方法是什么?

更新:

此处的示例压缩:https://github.com/MonoReports/MonoReports/zipball/master

重复:https://github.com/MonoReports/MonoReports/tree/master/src/MonoReports.Model/DataSourceType.cshttps://github.com/MonoReports/MonoReports/tree/master/src/MonoReports.Model/DatasourceType.cs

以下是有关异常的更多详细信息:

Ionic.Zip.ZipException:无法将其读取为 ZipFile
---> System.ArgumentException:已添加具有相同键的>项。
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource(
at System.Collections.Generic.Dictionary 2.Insert(TKey key, TValue value, Boolean add)
at System.Collections.Generic.Dictionary
2.Add(TKey key, TValue value(
at Ionic.Zip.ZipFile.ReadCentralDirectory(ZipFile zf(
at Ionic.Zip.ZipFile.ReadIntoInstance(ZipFile zf(

分辨率:

根据@Cheeso的建议,我可以从流中读取所有内容,避免重复和路径问题:

//using (ZipFile zip = ZipFile.Read(path))
using (ZipInputStream stream = new ZipInputStream(path))
{
    ZipEntry e;
    while( (e = stream.GetNextEntry()) != null )
    //foreach( ZipEntry e in zip)
    {
        if (e.FileName.ToLower().EndsWith(".cs") ||
            e.FileName.ToLower().EndsWith(".xaml"))
        {
            //var ms = new MemoryStream();
            //e.Extract(ms);
            var sr = new StreamReader(stream);
            {
                //ms.Position = 0;
                CodeFiles.Add(new CodeFile() { Content = sr.ReadToEnd(), FileName = e.FileName });
            }
        }
    }
}

对于PathTooLongException问题,我发现你不能使用DotNetZip。相反,我所做的是调用 7-zip 的命令行版本;这创造了奇迹。

public static void Extract(string zipPath, string extractPath)
{
    try
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo
        {
            WindowStyle = ProcessWindowStyle.Hidden,
            FileName = Path.GetFullPath(@"7za.exe"),
            Arguments = "x "" + zipPath + "" -o"" + extractPath + """
        };
        Process process = Process.Start(processStartInfo);
        process.WaitForExit();
        if (process.ExitCode != 0) 
        {
            Console.WriteLine("Error extracting {0}.", extractPath);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Error extracting {0}: {1}", extractPath, e.Message);
        throw;
    }
}

ZipInputStream阅读它。

ZipFile类使用文件名作为索引来保存集合。重复的文件名会破坏该模型。

但是您可以使用ZipInputStreamZipFile中阅读。在这种情况下,没有集合或索引。

最新更新