How to check whether file exists in zip file using dotnetzip

笑着哭i 提交于 2019-12-30 09:34:25

问题


I am creating zip using dotnetzip library.

But I don't know how to check if a file exists in the zip. If the file exists then I will update the file with path.

    public void makezip(string flname)
   {
      string  fln =flname;
        string curFile = @"d:\crs.zip";
        if (File.Exists(curFile))
        {
                ZipFile zipfl = ZipFile.Read(@"D:\crs.zip");
            var result = zipfl.Any(entry => entry.FileName.EndsWith(@fln));
            if (result == true) {
                zipfl.UpdateFile(@fln);
                }else{
                  zipfl.AddFile(@fln);
                }
            zipfl.Save(@"d:\crs.zip");
        }
        else
        {
            try
            {
                ZipFile zipfl = new ZipFile();

                var result = zipfl.Any(entry => entry.FileName.EndsWith(@fln));
                if (result == true)
                {
                  zipfl.AddFile(@fln);
                }
                zipfl.Save(@"d:\crs.zip");
            }catch {
                MessageBox.Show("Invalid Zip File");

            }}}

回答1:


How to check whether file exists in zip file?

Just use LINQ Any, assume you have input zip file input.zip, to check whether input.zip contains input.txt:

 var zipFile = ZipFile.Read(@"C:\input.zip");
 var result = zipFile.Any(entry => entry.FileName.EndsWith("input.txt"));



回答2:


(This is not dotnetzip but will get the job done.)

Requires: using System.IO.Compression;

Assembly: System.IO.Compression.FileSystem.dll

public static bool ZipHasFile(string fileFullName, string zipFullPath)
{
    using (ZipArchive archive = ZipFile.OpenRead(zipFullPath))  //safer than accepted answer
    {
        foreach (ZipArchiveEntry entry in archive.Entries)
        {
            if (entry.FullName.EndsWith(fileFullName, StringComparison.OrdinalIgnoreCase))
            {
                return true;
            }
        }
    }
    return false;
}

Example call: var exists = ZipHelper.ZipHasFile(@"zipTest.txt", @"C:\Users\...\Desktop\zipTest.zip");



来源:https://stackoverflow.com/questions/12553809/how-to-check-whether-file-exists-in-zip-file-using-dotnetzip

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!