You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用ZipFile.CreateEntryFromFile压缩时为文件添加.pdf扩展名?

Solution: Add .PDF Extension to Zip Entries

Absolutely, you can easily add the .pdf extension to each file when creating entries in the zip archive. The key change is modifying the entry name parameter in the CreateEntryFromFile method—this is what determines the filename that will appear when the zip is extracted.

Here's your updated code with the extension added:

using (var zip = ZipFile.Open(zipPath, ZipArchiveMode.Create)) 
{ 
    foreach (var filePath in files) 
    { 
        if (File.Exists(filePath.Value)) 
        { 
            // Append ".pdf" to the entry name to ensure it's recognized as a PDF after extraction
            string zipEntryName = filePath.Key + ".pdf";
            zip.CreateEntryFromFile(filePath.Value, zipEntryName); 
        } 
    } 
}

How this works:

  • The filePath.Value remains the path to your server-side file (without an extension)
  • We create a new zipEntryName by appending .pdf to filePath.Key—this becomes the filename inside the zip
  • When users extract the zip, each file will have the .pdf extension, so their OS will recognize it as a PDF document and open it with the appropriate application

If there's any chance some entries might already have an extension (though you mentioned all are PDF without extensions), you could add a quick check to avoid duplicate extensions, but based on your description, this simple modification should work perfectly.

内容的提问来源于stack exchange,提问作者stackoverfloweth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 10:06:51