如何在使用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.Valueremains the path to your server-side file (without an extension) - We create a new
zipEntryNameby appending.pdftofilePath.Key—this becomes the filename inside the zip - When users extract the zip, each file will have the
.pdfextension, 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
相关产品推荐
相关产品推荐

