如何在NSIS中创建ZIP文件?运行时打包待安装文件方案咨询
Great questions about NSIS ZIP handling! Let's tackle them one by one.
Since you noted that the ZipDLL plugin only supports extraction, here are two reliable alternatives for compression:
ZipArchive Plugin
This lightweight plugin is purpose-built for ZIP file creation and manipulation in NSIS. Here's a practical example:
!include "ZipArchive.nsh" ; Ensure this include file is in your NSIS include directory Section "Generate ZIP Archive" ; Step 1: Create a temporary folder to hold files for compression CreateDirectory "$TEMP\TempInstallAssets" ; Step 2: Extract your installer's files to the temp folder (adjust paths to match your project) File /oname="$TEMP\TempInstallAssets\user-guide.pdf" "src\user-guide.pdf" File /oname="$TEMP\TempInstallAssets\main-app.exe" "src\main-app.exe" ; Step 3: Create and populate the ZIP file ZipArchive::Create "$INSTDIR\InstalledAssets.zip" ; Define the output ZIP path ZipArchive::AddFile "$TEMP\TempInstallAssets\user-guide.pdf" "docs/user-guide.pdf" ; Add file with internal subpath ZipArchive::AddFile "$TEMP\TempInstallAssets\main-app.exe" "main-app.exe" ; Add file to the ZIP root ZipArchive::Close ; Finalize the ZIP compression ; Step 4: Clean up temporary files RMDir /r "$TEMP\TempInstallAssets" SectionEnd
7-Zip Plugin
If you need support for multiple archive formats (not just ZIP) or want advanced compression controls, the 7-Zip plugin is a powerful choice. It uses the 7-Zip command-line tool under the hood:
!include "7z.nsh" ; Include the 7-Zip plugin definitions Section "Create ZIP with 7-Zip" CreateDirectory "$TEMP\TempInstallAssets" ; Batch extract all installer files to the temporary directory File /oname="$TEMP\TempInstallAssets\*.*" "src\*.*" ; Use 7-Zip to create a ZIP: `-tzip` specifies ZIP format, `-mx9` enables maximum compression ExecWait '"$PLUGINSDIR\7z.exe" a -tzip -mx9 "$INSTDIR\FullInstallArchive.zip" "$TEMP\TempInstallAssets\*"' ; Clean up temporary files RMDir /r "$TEMP\TempInstallAssets" SectionEnd
Absolutely! The key detail here is that installer files are stored in the NSIS package's data segment—you can't compress them directly from there. Instead, you'll first extract them to a temporary directory, then compress that directory's contents.
The examples above already demonstrate this workflow:
- Extract your target files to a temporary folder using
File /oname=... - Run your chosen compression plugin/tool on the temp folder
- Clean up the temp files once the ZIP is created
This logic runs smoothly during the installer's runtime, so you can trigger it in a section that runs after initial setup, or integrate it directly into the main installation flow.
内容的提问来源于stack exchange,提问作者Bella

