zip.AddFiles() 处理目录中不存在的文件,只需跳过这些文件并压缩其他现有文件

zip.AddFiles() handle not existing files on the directory just skip those files and zip others existing

try
  {
  Response.Clear();
  Response.BufferOutput = false;
  string archiveName = String.Format("arch{0}.zip",                                  DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
  Response.ContentType = "application/zip";
  Response.AddHeader("content-disposition", "filename=" + archiveName);

    using (ZipFile zip = new ZipFile())
    {                                        
     zip.AddFiles(ListOfPastPapers,"PastPapers");                    
     zip.Save(Response.OutputStream);
     Response.Close();
    }
   }
catch (System.Exception ex1)
 {                 
 }

我正在使用 Ionic.Zip dll 压缩图像。我将字符串类型的列表提供给具有完整服务器路径的 zip.addfiles() 当找不到特定路径上的任何图像时它会抛出异常。

我该如何处理?

如果图像不存在,我想要的只是跳过该图像并压缩所有其他现有图像。

我该怎么做?

File.Exists(string) 甚至 FileInfo.Exists 对您的情况都有帮助。对于不存在的情况,只需跳到下一个迭代。

添加文件前请检查文件是否存在

using (ZipFile zip = new ZipFile())
{  

 foreach(var name in ListOfPastPapers)
 {
    if(System.IO.File.Exists(name))
    {
       zip.AddFiles(filePath,"PastPapers");                    
       zip.Save(Response.OutputStream);
       Response.Close();
     }
   }
}