I want to temporarily add a directory to the DLL search path - is there a proper way to do this in Windows 7?
Scenario
I have a C # application, let it WonderApp.
WonderApp needs to call the C ++ DLL located in C:\MyPath . So, as part of the WonderApp Program.Main() , I added the following command:
Environment.SetEnvironmentVariable("PATH", "C:\\MyPath;" + Environment.GetEnvironmentVariable("PATH"));
According to this article , adding a directory to PATH should also add it to the directory search for DLLs.
The solution works fine in Windows XP: if I add the directory to PATH , the DLL will load and the program will work fine. If I do not add the directory, the DLL does not load, with a "not found" error.
However, this does not work for Windows 7.
So, I decided, let him try using SetDllDirectory() . Like this:
[System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError = true)] private static extern bool SetDllDirectory(string lpPathName);
And, later:
bool success = SetDllDirectory(Util.Paths.GetApplicationDataDir());
success is true , but the dll is still not loading.
Finally, if I set PATH to enable C:\MyPath manually, before running the application - it all works! The DLL loads and works very well.
So for re-iteration:
Is there a correct way to temporarily add a directory to a DLL search path in Windows 7?
UPDATE:. Using Process Explorer, I checked the application runtime, and "C: \ MyPath" really was in PATH ! In addition, I saw that Helper.dll was on the list of open descriptors (as a DLL, not just a file), and it still claimed to not find it.