繁体   English   中英

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

[英]An item with the same key has already been added 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 相同的方式更改文件名。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM