Search code examples
c#.netwindowspinvokedllimport

.net DllImport issue


I'm loading a dll with DllImport and the name of the dll (as it is in the same folder as my application):

[DllImport("myDll.dll")]

and till here all works fine if application is opened from the same location. But if I run cmd and type:

"C:\path\to\my\application\app.exe"

the application opens but the dll called from the application itself isn't loaded anymore.

So to sum up if I open manually app.exe from C:\path\to\my\application\ the DllImport works fine and loads the dll in the same path. If I open the application from another location, it isn't loaded anymore.

Any suggestions? Tried also

[DllImport("C:\\path\\to\\my\\application\\myDll.dll")]

and

[DllImport("\\myDll.dll")]

but no way, it doesn't work.


Solution

  • The DLL is located using the DLL search order, as described here: http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586.aspx. Since the DLL is in the same directory as the executable, it will be found because the directory containing the executable is the first place that the system searches.

    So we can conclude that the DLL is found by the loader. Since you report that the behaviour changes when the working directory changes it would seem that is the problem. Your DLL has a dependency on the working directory. It's probably a mistake to have such a dependency. You should find a way to avoid such a dependency.