c# sharpziplib将文件添加到现有的压缩文档

.Net技术 针尖舞 10年前 (2014-07-26) 19542次浏览 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();
            }
        }
15票
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();
}

如果你想添加一个文件集合,使用addfile()。

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() 或其他。

2票
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);

这是不正确的,size 是 newFileStream.length ,Read读取错误.
比如你有一个 10-1 = 9 bytes 长的数组, 应该从 0 to 8读取
但是你从0到9读的…

1票
我认为你的 Finish调用应该在你的Close 调用之前
更新: 好像有一个 已知的bug.可能已经被修复- 你需要检查你的SharpZipLib版本是否包含任何修复。如果没有,你可以通过如下方法解决它:复制所有文件到一个新的压缩文档,添加新文件,然后用旧的压缩文件名命名新的压缩文件。
1票
    /// <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();
    }
 
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
和其他文件夹
文件 –> customer.pdf, sample.doc

 
ZipOutputStream 类不会更新现有的ZIP文件。使用ZipFile 类替代
 
我发现一个保持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();

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明c# sharpziplib将文件添加到现有的压缩文档
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!