简体   繁体   English

从嵌入式资源加载程序集

[英]Load an assembly from an embedded resource

I would like to load a dll file (Test.dll) as an assembly. 我想加载一个DLL文件(Test.dll)作为程序集。 I am able to do this using both direct Visual Studio references (ie. loading the dll as a reference to my C# application) as well as loading the dll using the Assembly.LoadFile(filename) method. 我可以使用直接的Visual Studio引用(即加载dll作为对我的C#应用​​程序的引用)以及使用Assembly.LoadFile(filename)方法加载dll。 Now, I would like to add my dll file as an embedded resource to my Visual Studio application, and load the dll file as an assembly. 现在,我想将我的dll文件作为嵌入式资源添加到我的Visual Studio应用程序中,并将dll文件作为程序集加载。 I know how to load this resource as a byte array, is there some correlation between the byte array and the assembly that I could use? 我知道如何将此资源作为字节数组加载,字节数组和我可以使用的程序集之间是否存在某种关联? Furthermore, I need to be able to call a method located within the dll file. 此外,我需要能够调用位于dll文件中的方法。 See the code below - it will further explain what I am doing. 请参阅下面的代码 - 它将进一步解释我在做什么。

Assembly SampleAssembly = Assembly.LoadFrom("WindowsFormsApplication2.ThisisaTESTDLL.dll");
Type myType = SampleAssembly.GetTypes()[0];
MethodInfo Method = myType.GetMethod("myVoid");
object myInstance = Activator.CreateInstance(myType,null);
Method.Invoke(myInstance,new object[] { "param1", "param1"});

If I am missing anything here, please respectfully let me know and I will edit the original post. 如果我在这里遗漏任何东西,请尊敬地告诉我,我将编辑原始帖子。

Assembly.GetExecutingAssembly().GetManifestResourceStream(...) Assembly.GetExecutingAssembly()。GetManifestResourceStream(...)

That should get you a Stream object. 这应该会得到一个Stream对象。 You can read a byte array from that. 你可以从中读取一个字节数组。

You can load that using Assembly.Load 您可以使用Assembly.Load加载它

I embedded AxInterop.WMPLib.dll and Interop.WMPLib.dll into my exe and got them loaded by using the following code. 我将AxInterop.WMPLib.dll和Interop.WMPLib.dll嵌入到我的exe中,并使用以下代码加载它们。 The code is placed just at the beginning of static void Main() in Program.cs file. 代码放在Program.cs文件中静态void Main()的开头。 Target framework is .NET 3.5 in my case. 在我的案例中,目标框架是.NET 3.5。 This code helped me bundle the dlls into the exe itself without having to deploy them through installers. 这段代码帮助我将dll捆绑到exe本身,而无需通过安装程序进行部署。 I have hardcoded my names. 我硬编了我的名字。 In the code below "res" is the name of my resource "res.resx" that contains the two embedded dlls. 在下面的代码中,“res”是包含两个嵌入式dll的资源“res.resx”的名称。

AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(    
(s, a) =>
{
    if (a.Name.Substring(0, a.Name.IndexOf(",")) == "AxInterop.WMPLib")
    {
        return Assembly.Load(res.AxInterop_WMPLib);
    }

    if (a.Name.Substring(0, a.Name.IndexOf(",")) == "Interop.WMPLib")
    {
        return Assembly.Load(res.Interop_WMPLib);
    }

    return null;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM