c# - 使用 CSharpCodeProvider 时在构建中嵌入依赖项
问题描述
我在运行时在我的程序中使用 编译 C# 程序集CSharpCodeProvider
,这取决于一些构建为.dll
s 的库,以及构建它的程序。
理想情况下,我只想构建一个可执行文件,而不必复制所有依赖项。
这是我用来编译程序集的代码:
//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();
推荐阅读
- azure - Azure 服务总线 - 多个订阅者不会收到所有消息
- excel-formula - Excel公式使单元格只读
- java - 保存更多 10 个项目的 ArrayList 未排序到 DB
- callback - 我在哪里可以找到无限网格存储的其他回调?
- oracle12c - 如何从 SOA Web 服务调用中解锁 IBM 内容导航器中的对象
- c# - 为什么 JWT 过期太快
- excel - 如何从 Excel VBA 代码触发 Access 数据库表单中的单击
- asp.net-mvc - 如果 IIS 应用程序工作进程挂起会怎样?
- python - 多线程时循环不使用新变量运行
- java - 我们使用@inject 时的默认范围是什么