0

我正在尝试基于多项选择下载 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();
4

1 回答 1

1

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

尝试用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 相同的方式更改文件名。

然后,您无需在文件名中包含时间以确保唯一性。

于 2021-06-15T14:07:39.070 回答