问题描述
我正在尝试使用以下代码将文件添加到现有存档中.运行时不会显示错误或异常,但也不会将文件添加到存档中.任何想法为什么?
am trying to add a file to an existing archive using the following code. When run no errors or exceptions are shown but no files are added to the archive either. Any ideas why?
using (FileStream fileStream = File.Open(archivePath, FileMode.Open, FileAccess.ReadWrite))
using (ZipOutputStream zipToWrite = new ZipOutputStream(fileStream))
{
zipToWrite.SetLevel(9);
using (FileStream newFileStream = File.OpenRead(sourceFiles[0]))
{
byte[] byteBuffer = new byte[newFileStream.Length - 1];
newFileStream.Read(byteBuffer, 0, byteBuffer.Length);
ZipEntry entry = new ZipEntry(sourceFiles[0]);
zipToWrite.PutNextEntry(entry);
zipToWrite.Write(byteBuffer, 0, byteBuffer.Length);
zipToWrite.CloseEntry();
zipToWrite.Close();
zipToWrite.Finish();
}
}
推荐答案
在 DotNetZip 中,将文件添加到现有zip 非常简单可靠.
In DotNetZip, adding files to an existing zip is really simple and reliable.
using (var zip = ZipFile.Read(nameOfExistingZip))
{
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.AddFile(additionalFileToAdd);
zip.Save();
}
如果要为该新文件指定目录路径,请为 AddFile() 使用不同的重载.
If you want to specify a directory path for that new file, then use a different overload for AddFile().
using (var zip = ZipFile.Read(nameOfExistingZip))
{
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.AddFile(additionalFileToAdd, "directory\\For\\The\\Added\\File");
zip.Save();
}
如果要添加一组文件,请使用 AddFiles().
If you want to add a set of files, use AddFiles().
using (var zip = ZipFile.Read(nameOfExistingZip))
{
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
zip.AddFiles(listOfFilesToAdd, "directory\\For\\The\\Added\\Files");
zip.Save();
}
您不必担心 Close()、CloseEntry()、CommitUpdate()、Finish() 或任何其他垃圾.
You don't have to worry about Close(), CloseEntry(), CommitUpdate(), Finish() or any of that other gunk.
这篇关于c#Sharpziplib将文件添加到现有存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!