如何将附属程序集嵌入到 EXE 文件中
-
12-09-2019 - |
题
我遇到的问题是,我需要将 C# 项目作为单个 EXE 文件分发,该文件不是安装程序,而是真正的程序。它还需要包含当前位于子目录中的翻译。
是否可以将其直接嵌入到二进制文件中?
解决方案
这是我在网上看到的最简单的解决方案:
该解决方案的实现也很方便:http://code.google.com/p/costura/wiki/HowItWorksEmbedTask
其他提示
简短的回答是肯定的,有一个称为集链接器(AL程序。 EXE)会以这种方式嵌入组件。它的主要用途的情况是本地化,听起来好像这是你需要它了。如果是的话,它应该是简单的。
例如:
人/吨:LIB /embed:strings.de.resources /培养:德/out:MyApp.resources.dll
或
Al.exe工具/培养:EN-US /out:bin\Debug\en-US\HelloWorld.resources.dll /embed:Resources\MyResources.en-US.resources,HelloWorld.Resources.MyResources.en-US的.resources /template:bin\Debug\HelloWorld.exe
另一种选择是嵌入其他组件作为EmbededResource。然后处理应用程序域AssemblyResolve,从这里你可以阅读从资源组装,并将其加载到运行时。类似如下:
public class HookResolver
{
Dictionary<string, Assembly> _loaded;
public HookResolver()
{
_loaded = new Dictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}
System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string name = args.Name.Split(',')[0];
Assembly asm;
lock (_loaded)
{
if (!_loaded.TryGetValue(name, out asm))
{
using (Stream io = this.GetType().Assembly.GetManifestResourceStream(name))
{
byte[] bytes = new BinaryReader(io).ReadBytes((int)io.Length);
asm = Assembly.Load(bytes);
_loaded.Add(name, asm);
}
}
}
return asm;
}
}
不隶属于 StackOverflow