[英]How to check whether file exists in zip file using dotnetzip
I am creating zip using dotnetzip library. 我正在使用dotnetzip库创建zip。
But I don't know how to check if a file exists in the zip. 但我不知道如何检查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");
}}}
How to check whether file exists in zip file? 如何检查zip文件中是否存在文件?
Just use LINQ Any
, assume you have input zip file input.zip
, to check whether input.zip
contains input.txt
: 只需使用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"));
(This is not dotnetzip but will get the job done.) (这不是dotnetzip,但会完成工作。)
Requires: using System.IO.Compression;
需要: using System.IO.Compression;
Assembly: System.IO.Compression.FileSystem.dll 汇编: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");
示例调用: var exists = ZipHelper.ZipHasFile(@"zipTest.txt", @"C:\\Users\\...\\Desktop\\zipTest.zip");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.