2

我使用此代码将所有 dll 嵌入到应用程序 exe 文件中,但此代码只能嵌入一个 dll。我搜索其他代码,但都是一样的。

public App()
{
    AppDomain.CurrentDomain.AssemblyResolve +=new ResolveEventHandler(CurrentDomain_AssemblyResolve);
}

System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll","");

    dllName = dllName.Replace(".", "_");

    if (dllName.EndsWith("_resources")) return null;

    System.Resources.ResourceManager rm = new System.Resources.ResourceManager(GetType().Namespace + ".Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());

    byte[] bytes = (byte[])rm.GetObject(dllName);

    return System.Reflection.Assembly.Load(bytes);
}

要使用 ILmerge,我的 dll 有问题。所以我不能用这个。我怎样才能做到这一点?

4

3 回答 3

0

使用 GetManifestResourceStream 应该会更好。

当 dll 作为资源嵌入时,资源名称的前缀是您项目的默认名称空间,因此您需要填写它。

例如

static  System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
    string defaultNameSpace = "...";

    string dllName = args.Name.Contains(',') ? args.Name.Substring(0, args.Name.IndexOf(',')) : args.Name.Replace(".dll", "");

    string resourceName = String.Format("{0}.{1}.dll", defaultNameSpace , dllName);

    using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName))
    {
         if (stream == null)  
             return null;

         byte[] data = new byte[stream.Length];
         stream.Read(data, 0, data.Length);
         return Assembly.Load(data);
     }
 }
于 2012-09-01T10:44:00.077 回答
0

这个开源工具应该可以帮助你

http://madebits.com/netz/

于 2012-09-01T10:24:13.120 回答
0

一种可能的方法是将所有 DLL 添加到资源中(手动)。然后,在程序启动时,使用File.WriteAllBytes将这些资源字节流写入文件。

注意:在这种情况下,您不能使用DllImport,因为它需要常量字符串路径。相反,您将使用所谓的“动态 P\Invoke”。学到更多。

于 2012-09-01T10:30:20.797 回答