簡體   English   中英

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

[英]How to check whether file exists in zip file using 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");

            }}}

如何檢查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"));

(這不是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;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM