Specify the search path for DllImport in .NET.

Is there a way to specify search paths for a given assembly imported using DllImport?

[DllImport("MyDll.dll")] static extern void Func(); 

This will search for the dll in the app directory and in the PATH environment variable. But from time to time the dll will be placed elsewhere. Can this information be provided in the app.config or manifest file to avoid dynamic loading and dynamic invocation?

+52
dllimport
May 19 '10 at 10:34 a.m.
source share
3 answers

Call SetDllDirectory with your additional DLL paths before you SetDllDirectory imported function for the first time.

P / Invoke Signature:

 [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetDllDirectory(string lpPathName); 



To specify more than one additional DLL search path, modify the PATH environment, for example:

 static void AddEnvironmentPaths(string[] paths) { string path = Environment.GetEnvironmentVariable("PATH") ?? string.Empty; path += ";" + string.Join(";", paths); Environment.SetEnvironmentVariable("PATH", path); } 

There is more information about the DLL search order here on MSDN .




Updated 2013/07/30:

Updated version above using Path.PathSeparator :

 static void AddEnvironmentPaths(IEnumerable<string> paths) { var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty }; string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths)); Environment.SetEnvironmentVariable("PATH", newPath); } 
+65
May 19 '10 at 10:39
source share

Try calling AddDllDirectory with your additional DLL paths before calling the imported function for the first time.

If your version of Windows is lower than 8, you need to install this patch , which extends the API with the AddDllDirectory function AddDllDirectory for Windows 7, 2008 R2, 2008 and Vista (although there is no patch for XP).

+14
May 29 '12 at 13:35
source share

It may be useful. DefaultDllImportSearchPathsAttribute Class
For example.

 [assembly: DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)] 

Also note that you can use AddDllDirectory , so that you are not chewing anything:

 [DllImport("kernel32.dll", SetLastError = true)] static extern bool AddDllDirectory(string path); 
+1
Jul 29 '17 at 2:55
source share



All Articles