如何在使用Ionic.Zip.ZipFile保存到磁盘之前获得zip文件的大小

本文关键字:zip 文件 磁盘 Ionic 保存 ZipFile Zip | 更新日期: 2023-09-27 18:17:19

我使用的是ionic . zip . zipfile,我想创建一个10mb的zip文件。我需要在保存到磁盘之前得到ZipFile的大小。这可能吗?

    private static string tempPath = "@Temp Folder";
    List<string> fileNames = new List<string>();

    using (Ionic.Zip.ZipFile zf = new Ionic.Zip.ZipFile())
    {
      for (int i = 0; i < fileNames.Count; i++)
      {
        zf.AddFile(tempPath + fileNames[i], string.Empty);
        //How can I get size of zf before save here ?
      if(zf size==10mb)
      {
       zf.Save(tempPath + string.Format("{0}-{1}-{2}.zip","XXX", "XXX", 
          DateTime.Now.ToString("yyyyMMdd")));
      }
     }
   }

如何在使用Ionic.Zip.ZipFile保存到磁盘之前获得zip文件的大小

您可以将您的zip文件保存到MemoryStream:

var ms = new MemoryStream();
zip.Save(ms);

然后读取MemoryStream。长度属性并获取长度

如果你仍然想把它保存到磁盘上,就使用你已经拥有的内存流:

FileStream file = new FileStream("file.zip", FileMode.Create, FileAccess.Write);
// I believe you'll need to rewind the stream before saving
ms.Seek(0, SeekOrigin.Begin); 
ms.WriteTo(file);
file.Close();
ms.Close();