C# Sharpziplib 将文件添加到现有存档

发布于 2024-08-03 20:26:36 字数 867 浏览 7 评论 0原文

我正在尝试使用以下代码将文件添加到现有存档中。运行时不会显示错误或异常,但也不会将文件添加到存档中。有什么想法吗?

        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();
            }
        }

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();
            }
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

长亭外,古道边 2024-08-10 20:26:36

DotNetZip 中,将文件添加到现有 zip 中非常简单且可靠。

using (var zip = ZipFile.Read(nameOfExistingZip))
{
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
    zip.AddFile(additionalFileToAdd);
    zip.Save();
}

如果要为该新文件指定目录路径,请对 AddFile() 使用不同的重载。

using (var zip = ZipFile.Read(nameOfExistingZip))
{
    zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
    zip.AddFile(additionalFileToAdd, "directory\\For\\The\\Added\\File");
    zip.Save();
}

如果要添加一组文件,请使用 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() 或任何其他问题。

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();
}

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();
}

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();
}

You don't have to worry about Close(), CloseEntry(), CommitUpdate(), Finish() or any of that other gunk.

戈亓 2024-08-10 20:26:36

从 Codeproject 有人使用了这段代码。唯一的区别是接近并以其他方式完成和写入部分:

using (ZipOutputStream s = new
ZipOutputStream(File.Create(txtSaveTo.Text + "\\" +
sZipFileName + ".zip")))
{
    s.SetLevel(9); // 0-9, 9 being the highest compression

    byte[] buffer = new byte[4096];

    foreach (string file in filenames)
    {

        ZipEntry entry = new
        ZipEntry(Path.GetFileName(file));

        entry.DateTime = DateTime.Now;
        s.PutNextEntry(entry);

        using (FileStream fs = File.OpenRead(file))
        {
            int sourceBytes;
            do
            {
                sourceBytes = fs.Read(buffer, 0,
                buffer.Length);

               s.Write(buffer, 0, sourceBytes);

            } while (sourceBytes > 0);
        }
    }
    s.Finish();
    s.Close();
}

顺便说一句:

byte[] byteBuffer = new byte[newFileStream.Length - 1];

                newFileStream.Read(byteBuffer, 0, byteBuffer.Length);

这是不正确的,大小是 newFileStream.length 否则读取会出错。
你有一个数组,例如 10-1 是 9 个字节长,从 0 到 8。

但是你的读数是从 0 到 9...

From Codeproject someone used this code. Only difference is close and finish otherway around and the write part:

using (ZipOutputStream s = new
ZipOutputStream(File.Create(txtSaveTo.Text + "\\" +
sZipFileName + ".zip")))
{
    s.SetLevel(9); // 0-9, 9 being the highest compression

    byte[] buffer = new byte[4096];

    foreach (string file in filenames)
    {

        ZipEntry entry = new
        ZipEntry(Path.GetFileName(file));

        entry.DateTime = DateTime.Now;
        s.PutNextEntry(entry);

        using (FileStream fs = File.OpenRead(file))
        {
            int sourceBytes;
            do
            {
                sourceBytes = fs.Read(buffer, 0,
                buffer.Length);

               s.Write(buffer, 0, sourceBytes);

            } while (sourceBytes > 0);
        }
    }
    s.Finish();
    s.Close();
}

BTW:

byte[] byteBuffer = new byte[newFileStream.Length - 1];

                newFileStream.Read(byteBuffer, 0, byteBuffer.Length);

This is incorrect, the size is newFileStream.length else the Read goes wrong.
You have an array and you make it for example 10-1 is 9 bytes long, from 0 to 8.

But your reading from 0 to 9...

秉烛思 2024-08-10 20:26:36

我认为您的 Finish 调用应该您的 Close 调用之前。

更新:这看起来像已知错误。它可能已经被修复 - 您需要检查您的 SharpZipLib 版本以查看它是否包含任何修复。如果没有,您可以通过将所有文件复制到新存档,添加新文件,然后将新存档移动到旧存档名称来解决此问题。

I think your Finish call should be before your Close call.

Update: This looks like a known bug. It's possible it may already have been fixed - you'll need to check your SharpZipLib version to see if it incorporates any fix. If not, you can work around it by copying all files to a new archive, adding the new file, then moving the new archive to the old archive name.

茶花眉 2024-08-10 20:26:36
    /// <summary>
    /// 添加压缩文件 p 为客户端传回来的文件/夹列表,用分号隔开,不包括主路径, zipfile压缩包的名称
    /// </summary>
    /// <param name="p"></param>
    /// <param name="zipfile"></param>
    public void AddZipFile(string p, string zipfile)
    {
        if (ServerDir.LastIndexOf(@"\") != ServerDir.Length - 1)
        {
            ServerDir += @"\";
        }
        string[] tmp = p.Split(new char[] { ';' }); //分离文件列表
        if (zipfile != "") //压缩包名称不为空
        {
            string zipfilepath=ServerDir + zipfile;
            if (_ZipOutputStream == null)
            {
                _ZipOutputStream = new ZipOutputStream(File.Create(zipfilepath));
            }
            for (int i = 0; i < tmp.Length; i++)
            {
                if (tmp[i] != "") //分离出来的文件名不为空
                {
                    this.AddZipEntry(tmp[i], _ZipOutputStream, out _ZipOutputStream); //向压缩文件流加入内容
                }
            }
        }
    }
    private static ZipOutputStream _ZipOutputStream;
    public void Close()
    {
        _ZipOutputStream.Finish();
        _ZipOutputStream.Close();
    }
    /// <summary>
    /// 添加压缩文件 p 为客户端传回来的文件/夹列表,用分号隔开,不包括主路径, zipfile压缩包的名称
    /// </summary>
    /// <param name="p"></param>
    /// <param name="zipfile"></param>
    public void AddZipFile(string p, string zipfile)
    {
        if (ServerDir.LastIndexOf(@"\") != ServerDir.Length - 1)
        {
            ServerDir += @"\";
        }
        string[] tmp = p.Split(new char[] { ';' }); //分离文件列表
        if (zipfile != "") //压缩包名称不为空
        {
            string zipfilepath=ServerDir + zipfile;
            if (_ZipOutputStream == null)
            {
                _ZipOutputStream = new ZipOutputStream(File.Create(zipfilepath));
            }
            for (int i = 0; i < tmp.Length; i++)
            {
                if (tmp[i] != "") //分离出来的文件名不为空
                {
                    this.AddZipEntry(tmp[i], _ZipOutputStream, out _ZipOutputStream); //向压缩文件流加入内容
                }
            }
        }
    }
    private static ZipOutputStream _ZipOutputStream;
    public void Close()
    {
        _ZipOutputStream.Finish();
        _ZipOutputStream.Close();
    }
等待我真够勒 2024-08-10 20:26:36

站点根目录中有一个文件夹ZippedFolder,里面有一个存档MyZipFiles

有一个名为 siteImages 的文件夹,其中包含所有图像文件。
以下是压缩图像的代码,

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip");
using (ZipFile zip = new ZipFile())
{
 zip.AddFile(Server.MapPath("~/siteImages/img1.jpg"),string.Empty);
 zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty);
 zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty);
 zip.Save(zipPath);
}

如果我们有不同的文件格式,并且我们希望您的文件保存在各自的文件夹中,您可以指定代码如下。

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip");
using (ZipFile zip = new ZipFile())
{
  zip.AddFile(Server.MapPath("~/siteimages/img1.jpg"), "images");
  zip.AddFile(Server.MapPath("~/siteimages/img2.jpg"), "images");
  zip.AddFile(Server.MapPath("~/documents/customer.pdf"), "files");
  zip.AddFile(Server.MapPath("~/documents/sample.doc"), "files");
  zip.Save(zipPath);
}

现在存档包含两个文件夹
图像 ----> img1.jpg , img2,.jpg
和另一个文件夹
文件 -->客户.pdf、样本.doc

there is a folder ZippedFolder in site's root directory , inside it we have a archive MyZipFiles.

There is a folder with name siteImages which consists of all image files.
The following is the code to zip the images

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip");
using (ZipFile zip = new ZipFile())
{
 zip.AddFile(Server.MapPath("~/siteImages/img1.jpg"),string.Empty);
 zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty);
 zip.AddFile(Server.MapPath("~/siteImages/img2.jpg"),string.Empty);
 zip.Save(zipPath);
}

if we have different file formats and we want your files to be saved in respective folders,you can specify the code as follows.

string zipPath = Server.MapPath("~/ZippedFolder/MyZipFiles.zip");
using (ZipFile zip = new ZipFile())
{
  zip.AddFile(Server.MapPath("~/siteimages/img1.jpg"), "images");
  zip.AddFile(Server.MapPath("~/siteimages/img2.jpg"), "images");
  zip.AddFile(Server.MapPath("~/documents/customer.pdf"), "files");
  zip.AddFile(Server.MapPath("~/documents/sample.doc"), "files");
  zip.Save(zipPath);
}

now the archive contains two folders
images ---- > img1.jpg , img2,.jpg
and another folder
files --> customer.pdf, sample.doc

椵侞 2024-08-10 20:26:36

ZipOutputStream 类不会更新现有的 ZIP 文件。请改用 ZipFile 类。

The ZipOutputStream class does not update existing ZIP files. Use the ZipFile class instead.

与之呼应 2024-08-10 20:26:36

我找到了一个简单的解决方案,仅将其保留为 ZipFile 和 ZipEntry

        ZipFile zipExisting = ZipFile.Read(Server.MapPath("/_Layouts/includes/Template.zip"));
        ICollection<ZipEntry> entries = _zipFileNew.Entries;
        foreach (ZipEntry zipfile in entries)
        {
            zipExisting.AddEntry(zipfile.FileName, zipfile.InputStream);
        } 

        zipExisting.Save(Response.OutputStream);
        Response.End();

I have found a simple solution keeping it to ZipFile and ZipEntry only

        ZipFile zipExisting = ZipFile.Read(Server.MapPath("/_Layouts/includes/Template.zip"));
        ICollection<ZipEntry> entries = _zipFileNew.Entries;
        foreach (ZipEntry zipfile in entries)
        {
            zipExisting.AddEntry(zipfile.FileName, zipfile.InputStream);
        } 

        zipExisting.Save(Response.OutputStream);
        Response.End();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文