简体   繁体   中英

Using reflection to call a DLL but another DLL required is throwing an exception

So i am using some reflection to call a function from a dll on a network drive. The problem is that the dll requires another dll and it is in that same folder but an exception is thrown.

Here is my code:

 try
        {
            Assembly loadedDLL = Assembly.LoadFrom(@"G:\Remote\Debug\BonderControlPanelSim.dll", AppDomain.CurrentDomain.Evidence);
            Type rtsObj = loadedDLL.GetType("Oe.Te.Ranorex.Instrument.BonderControlPanelSim");
            Object obj = Activator.CreateInstance(rtsObj);

            rtsObj.InvokeMember("Initialize", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { "COM3", 1, 2 });
            Thread.Sleep(1500);
            rtsObj.InvokeMember("PushStart", BindingFlags.InvokeMethod | BindingFlags.Public, null, obj, new object[] { "3" });
            Thread.Sleep(200);
            rtsObj.InvokeMember("Shutdown", BindingFlags.InvokeMethod | BindingFlags.Public, null, obj, null);

        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

The exception I get is this:

{"Unable to load DLL 'SeaMAX.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)"}

The SeaMAX.dll is required with the BonderControlPanelSim.dll.

My issue is that the dll is in the same folder... but my dll when reflection is used to invoke a member cant find the dll... but its there. Am I missing something

I think I'm familiar with this company and its products. This is unmanaged DLL, used for industrial I/O. The problem is that Windows cannot find the dependency, it isn't resolved by the CLR loader. You can help it by changing the current directory:

string oldPath = Environment.CurrentDirectory;
Environment.CurrentDirectory = @"G:\Remote\Debug";
Assembly loadedDLL = Assembly.LoadFrom(...);
Environment.CurrentDirectory = oldPath;
// etc..

This assumes seamax.dll is in the same directory as the assembly. It normally isn't. Pinvoking SetDllDirectory() is another trick, as is copying this DLL to a directory that's on the PATH environment variable.

My guess is that .net is not able to resolve the assembly reference. Attach to the AssemblyResolve Event of the AppDomain and load the assembly from the proper path : http://msdn.microsoft.com/en-us/library/system.appdomain.assemblyresolve(v=VS.90).aspx

  [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool SetDllDirectory(string dllPath);

SetDllDirectory(@"G:\\Remote\\Debug\\");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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