使用 CSharpCodeProvider 时在构建中嵌入依赖项

Embed dependencies in build when using CSharpCodeProvider

我在 运行 时间在我的程序中使用 CSharpCodeProvider 编译 C# 程序集,这取决于一些构建为 .dlls 的库,以及程序就是这样。

理想情况下,我只想构建一个可执行文件,而不必复制所有依赖项。

这是我用来编译程序集的代码:

//Create the compiler (with arguments).
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters cp = new CompilerParameters();
cp.GenerateExecutable = true;
cp.OutputAssembly = "example.exe";
cp.GenerateInMemory = false;

//Reference the main assembly (this one) when compiling.
Assembly entryasm = Assembly.GetEntryAssembly();
cp.ReferencedAssemblies.Add(entryasm.Location);

//Reference an external assembly it depends on.
cp.ReferencedAssemblies.Add("someExternal.dll");

//Attempt to compile.
CompilerResults results = provider.CompileAssemblyFromSource(cp, someScript);

此生成的可执行文件仍然需要 someExternal.dll 以及在 运行 时在同一目录中构建它的程序,我更希望它是包含所有依赖项的单个可执行文件。

有什么办法吗?

最后,我最终使用 ILRepack.Lib NuGet 包来完成这项工作,它允许您以编程方式合并二进制文件,无需使用命令行工具

这是我用来将目录中的所有 .dll 文件打包到可执行文件中的代码:

//Setting required options.
RepackOptions opt = new RepackOptions();
opt.OutputFile = "example_packed.exe";
opt.SearchDirectories = new string[] { AppDomain.CurrentDomain.BaseDirectory, Environment.CurrentDirectory };

//Setting input assemblies.
string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.dll");
opt.InputAssemblies = new string[] { "example.exe", entryasm.Location }.Concat(files).ToArray();

//Merging.
ILRepack pack = new ILRepack(opt);
pack.Repack();