gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:07:37 34 4
gpt4 key购买 nike

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

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

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

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

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

已更新:

示例 zip 来自这里: 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: Cannot read that as a ZipFile
---> System.ArgumentException: An > item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary2.Insert(TKey key, TValue value, Boolean add)<br/>
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 .相反,我所做的是调用 command-line version of 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;
}
}

关于c# - 如何使用太长/重复的路径处理解压缩 ZipFile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10677405/

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