开发者

Load an assembly from an embedded resource

I would like to load a dll file (Test.dll) as an assembly. 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. 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. 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. 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.GetMet开发者_运维知识库hod("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(...)

That should get you a Stream object. You can read a byte array from that.

You can load that using Assembly.Load


I embedded AxInterop.WMPLib.dll and Interop.WMPLib.dll into my exe and got them loaded by using the following code. The code is placed just at the beginning of static void Main() in Program.cs file. Target framework is .NET 3.5 in my case. This code helped me bundle the dlls into the exe itself without having to deploy them through installers. I have hardcoded my names. In the code below "res" is the name of my resource "res.resx" that contains the two embedded dlls.

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;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜