gpt4 book ai didi

c# - 将 zip 条目提取到另一个 Zip 文件

转载 作者:行者123 更新时间:2023-11-30 17:58:49 25 4
gpt4 key购买 nike

谁能告诉我为什么下面的代码不起作用?我正在为 Zip 流使用 SharpZipLib API,今天从他们的站点下载了最新版本。我试图使用此逻辑将一个 zip 文件的内容合并到另一个 zip 文件中,而不必在磁盘上执行 IO,因为预期的 zip 文件可能包含为 windows 保留的文件名。我已经尝试使用多个不同的源和目标 zip 文件(包含保留名称的文件和不包含保留名称的文件)。代码没有抛出任何异常,如果你在每次写入操作之前检查缓冲区,你可以看到它包含真实数据,但在整个操作完成后目标 zip 文件的大小没有改变,你可以探索它以确认没有新文件(代码应该添加的文件)实际上已添加到目标文件。 :(

    public static void CopyToZip(string inArchive, string outArchive)
{

ZipOutputStream outStream = null;
ZipInputStream inStream = null;
try
{
outStream = new ZipOutputStream(File.OpenWrite(outArchive));
outStream.IsStreamOwner = false;
inStream = new ZipInputStream(File.OpenRead(inArchive));
ZipEntry currentEntry = inStream.GetNextEntry();
while (currentEntry != null)
{

byte[] buffer = new byte[1024];
ZipEntry newEntry = new ZipEntry(currentEntry.Name);
newEntry.Size = currentEntry.Size;
newEntry.DateTime = currentEntry.DateTime;
outStream.PutNextEntry(newEntry);
int size = 0;
while ((size = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, size);
}
outStream.CloseEntry();

currentEntry = inStream.GetNextEntry();
}
outStream.IsStreamOwner = true;
}
catch (Exception e)
{
throw e;
}
finally
{
try { outStream.Close(); }
catch (Exception ignore) { }
try { inStream.Close(); }
catch (Exception ignore) { }
}
}

最佳答案

我最终使用不同的 API 来完成这项工作。 DotNet zip 来自 http://dotnetzip.codeplex.com/ .这是实现:

    public static void CopyToZip(string inArchive, string outArchive, string tempPath)
{
ZipFile inZip = null;
ZipFile outZip = null;

try
{
inZip = new ZipFile(inArchive);
outZip = new ZipFile(outArchive);
List<string> tempNames = new List<string>();
List<string> originalNames = new List<string>();
int I = 0;
foreach (ZipEntry entry in inZip)
{
if (!entry.IsDirectory)
{
string tempName = Path.Combine(tempPath, "tmp.tmp");
string oldName = entry.FileName;
byte[] buffer = new byte[4026];
Stream inStream = null;
FileStream stream = null;
try
{
inStream = entry.OpenReader();
stream = new FileStream(tempName, FileMode.Create, FileAccess.ReadWrite);
int size = 0;
while ((size = inStream.Read(buffer, 0, buffer.Length)) > 0)
{
stream.Write(buffer, 0, size);
}
inStream.Close();
stream.Flush();
stream.Close();
inStream = new FileStream(tempName, FileMode.Open, FileAccess.Read);

outZip.AddEntry(oldName, inStream);
outZip.Save();
}
catch (Exception exe)
{
throw exe;
}
finally
{
try { inStream.Close(); }
catch (Exception ignore) { }
try { stream.Close(); }
catch (Exception ignore) { }
}
}
}

}
catch (Exception e)
{
throw e;
}
}

关于c# - 将 zip 条目提取到另一个 Zip 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839502/

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