如何使用dotnetzip检查zip文件中是否存在文件

che*_*tan 5 c# compression dotnetzip

我正在使用dotnetzip库创建zip.

但我不知道如何检查zip中是否存在文件.如果该文件存在,那么我将使用路径更新该文件.

    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");

            }}}
Run Code Online (Sandbox Code Playgroud)

cuo*_*gle 9

如何检查zip文件中是否存在文件?

只需使用LINQ Any,假设您有输入zip文件input.zip,检查是否input.zip包含input.txt:

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


RGH*_*RGH 5

(这不是 dotnetzip,但可以完成工作。)

要求: using System.IO.Compression;

程序集: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;
}
Run Code Online (Sandbox Code Playgroud)

示例调用: var exists = ZipHelper.ZipHasFile(@"zipTest.txt", @"C:\Users\...\Desktop\zipTest.zip");