Specify the search path for DllImport in .NET

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

P/Invoke signature:

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

To set more than one additional DLL search path, modify the PATH environment variable, e.g.:

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

    Environment.SetEnvironmentVariable("PATH", path);
}

There’s more info about the DLL search order here on MSDN.


Updated 2013/07/30:

Updated version of the 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);
}

Leave a Comment