在.NET中指定DllImport的搜索路径

Ste*_*fan 53 .net dllimport

有没有办法为使用DllImport导入的给定程序集指定要搜索的路径?

[DllImport("MyDll.dll")]
static extern void Func();
Run Code Online (Sandbox Code Playgroud)

这将在app dir和PATH环境变量中搜索dll.但有时dll会放在其他地方.可以在app.config或清单文件中指定此信息以避免动态加载和动态调用吗?

Chr*_*ich 67

打电话SetDllDirectory与你额外的DLL路径,你打电话到首次导入功能之前.

P/Invoke签名:

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

要设置多个附加DLL搜索路径,请修改PATH环境变量,例如:

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

    Environment.SetEnvironmentVariable("PATH", path);
}
Run Code Online (Sandbox Code Playgroud)

有关MSDN上的DLL搜索顺序的更多信息.


更新 2013/07/30:

以上版本更新使用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);
}
Run Code Online (Sandbox Code Playgroud)

  • 你最好使用`Path.PathSeparator` (8认同)

小智 14

第一次调用AddDllDirectory导入的函数之前,请尝试使用其他DLL路径调用.

如果您的Windows版本低于8,则需要安装此修补程序,该修补程序扩展了API,缺少AddDllDirectoryWindows 7,2008 R2,2008和Vista的功能(尽管没有针对XP的补丁).


Eri*_*ric 7

这可能有用DefaultDllImportSearchPathsAttribute 类
,例如

[assembly: DefaultDllImportSearchPaths(DllImportSearchPath.UserDirectories)]
Run Code Online (Sandbox Code Playgroud)

另请注意,您也可以使用AddDllDirectory,这样您就不会搞砸已经存在的任何内容:

[StructLayout(LayoutKind.Sequential)]
struct DllDirectoryCookie { private nint value; }
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern DllDirectoryCookie AddDllDirectory(string path);
Run Code Online (Sandbox Code Playgroud)

并在你之后清理:

[StructLayout(LayoutKind.Sequential)]
struct BOOL { int value; /*...*/ operator bool(BOOL x) => x.value != 0; }
[DllImport("kernel32.dll", SetLastError = true)]
static extern BOOL RemoveDllDirectory(DllDirectoryCookie cookie);
Run Code Online (Sandbox Code Playgroud)