C#-Visual Studio:将DLL文件合并至EXE文件的方法
Absolutely, there are several straightforward ways to bundle those dozens of DLLs into a single EXE file—no more messy Release folders! Let’s walk through the most reliable methods for your C# console app in Visual Studio Community:
ILMerge is a Microsoft-backed utility designed specifically for merging .NET assemblies. Here’s how to use it:
- First, install the
ILMergepackage via NuGet in your project. - Right-click your project → Properties → Build Events → Post-build event command line. Add a command like this:
Replace"$(SolutionDir)packages\ILMerge.3.0.41\tools\net472\ILMerge.exe" /out:"$(TargetDir)YourMergedApp.exe" "$(TargetPath)" "$(TargetDir)*.dll"YourMergedApp.exewith your desired output filename, and adjust the ILMerge path to match the version you installed. - Build your Release version, and you’ll find the merged EXE in your target directory.
Fody is a compile-time weaving tool, and Costura is a plugin that automatically embeds all dependent DLLs into your EXE—they’re extracted and used at runtime without any extra work from you:
- Install the
Costura.Fodypackage via NuGet (no initial configuration needed; it works out of the box for most projects). - Simply build your project, and the main EXE in your Release folder will already contain all required DLLs.
- If you need to exclude specific DLLs, create or edit the
FodyWeavers.xmlfile in your project root with rules like:<Costura> <ExcludeAssemblies> <Assembly>UnwantedDllName</Assembly> </ExcludeAssemblies> </Costura>
If your project targets .NET Core 3.0 or later (including .NET 5/6/7/8), Visual Studio has built-in support for single-file publishing—no extra tools required:
- Right-click your project → Publish → Create a new profile, select "Folder" as the target.
- In the publish settings, check the "Produce single file" box. You can also enable "Enable compression" to reduce the final file size.
- Click Publish, and you’ll get a standalone EXE that includes all dependencies (even the .NET runtime if you select the "Self-contained" deployment mode).
- Some native (unmanaged) DLLs might not merge cleanly with these tools. For those, you’ll either need to keep them alongside the EXE or configure tools like Costura to embed them with additional setup.
- Always test the merged EXE thoroughly to ensure all dependencies load correctly.
- If using ILMerge, watch out for compatibility issues with strongly-named assemblies—you may need to adjust settings to handle them.
内容的提问来源于stack exchange,提问作者SKowalsky

