已经添加了一个具有相同密钥的项目C#-Ionic.Zip



我试图在多选的基础上下载zip文件,这意味着用户选择文档并按下下载文件按钮,然后生成zip文件。

一切正常。我的zip文件也在下载中。但有时,当我一次又一次地按下下载按钮时,会出现以下错误。我注意到,当我下载任何新文件时,都不会生成此错误。但是当我下载那些我已经下载了多次的文件时,这个错误就会生成

An item with the same key has already been added.

请注意,生成此错误的情况非常罕见。经过多次谷歌搜索,我似乎不明白为什么。我在下面发布我的代码。有人能帮我吗?

using (ZipFile zip = new ZipFile())
{  
foreach (DataRow row in dt.Rows)
{
//some code  
zip.AddFile(filePath, "files");   //here the error is 
generated
}
Response.Clear();
//Response.AddHeader("Content-Disposition", "attachment; filename=DownloadedFile.zip"); 
Response.ContentType = "application/zip";
zip.Save(Response.OutputStream);
Response.End();

如果在同一秒间隔内处理两个文件名,则将当前时间添加到文件名将无法确保唯一性。

尝试用以下代码替换zip.AddFile(filePath, "files");

while(true)
{
int i = 1;
string originalPath = filePath;
try
{
zip.AddFile(filePath, "files"); 
break;
}
catch (ArgumentException e)
{
filePath = string.Format(originalPath + " ({0})", i);
i++;
continue;
}
}

这将更改文件名,方法与Windows在尝试将文件复制到已存在文件名的文件夹中时所做的相同。

这样就不需要在文件名中包含时间来确保唯一性。

最新更新