I am aware of Window's equivalent "whereis" command from this article: https://superuser.com/questions/21067/windows-equivalent-of-whereis
But how does one perform the same using code? Is there a Windows API?
I am aware of Window's equivalent "whereis" command from this article: https://superuser.com/questions/21067/windows-equivalent-of-whereis
But how does one perform the same using code? Is there a Windows API?
This example code in C#, using Linq, shows how to scan the PATH environment variable:
static string SearchEnvPathForProgram(string filename)
{
return Environment.GetEnvironmentVariable("PATH").Split(';')
.Select(dir => Path.Combine(dir, filename))
.FirstOrDefault(path => File.Exists(path));
}
However, in case this is not sufficient for you and you need to mimic the complete behaviour of the CreateProcess
function of the windows kernel, you have to extend this function by adding the other places listed in the comment of @HarryJohnston (thanks for the remark).
For example, the folder of your current executable, the current directory, or the windows system directory. I guess you will find for each one a corresponding question here on SO.
LoadLibraryEx
followed by GetModuleFileName
is one option, although it will only work if the file name you're searching for includes the .exe
extension.
If safe DLL search mode is enabled (which it is by default on modern versions of Windows) you need to call SetDllDirectory
first, passing the current directory as the argument. Don't forget to call SetDllDirectory(NULL)
afterwards to restore the default behaviour.
This may not be safe in a multithreaded program, because another thread might load a DLL while safe search mode is disabled.