Load a dll from shared network drive in C#

2020-02-12 14:03发布

问题:

I am able to load the dll using this form -

System.Reflection.Assembly assembly =
System.Reflection.Assembly.LoadFile(@"C:\Users\amit.pandey\Documents\Visual Studio 2010\Projects\bin\Release\EUtility.dll");

However I need to load the dll from a shared network drive in the following manner -

System.Reflection.Assembly assembly =
System.Reflection.Assembly.LoadFile(@"\\falmumapp20\EUtility.dll");

I know it is caused because of trust problem. I have tried various code available but could not get it working. Can someone please help me with sample code for loading the dll from a network drive?

I want to do it in the code itself, without making change to any configuration file.

回答1:

Alternatively, loading the file from disk and calling Assembly.Load on the byte array seems to work (Framework 4):

        string Share = @"R:\Test\TestAssembly.dll";
        byte[] AssmBytes = File.ReadAllBytes(Share);
        Assembly a = Assembly.Load(AssmBytes);

        //Invoking a method from the loaded assembly
        var obj = a.CreateInstance("TestAssembly.Class1");
        obj.GetType().InvokeMember("HelloWorld", BindingFlags.InvokeMethod, null, obj, null);

Since MS blocks network loading in LoadFrom(), it would indicate that doing so is probably not best practices. However, this is similar to the process that is often used with embedding assemblies as resources in an EXE.



回答2:

You need to tell the machine to trust that location.

You can do this with the caspol utility.



回答3:

Instead of loading the binary content you can use Assembly.UnsafeLoadFrom. See http://msdn.microsoft.com/en-us/library/system.reflection.assembly.unsafeloadfrom%28v=vs.110%29.aspx

This worked fine for me in all purposes.



标签: c# dll