0

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?

Community
  • 1
  • 1
Johnny 5
  • 499
  • 5
  • 10

2 Answers2

2

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.

Community
  • 1
  • 1
Doc Brown
  • 19,739
  • 7
  • 52
  • 88
  • The algorithm Windows uses is more complicated; for example, the application directory is checked first, followed by the current directory. The path is at the bottom of the list, in sixth place. Full details in the [documentation for CreateProcess](http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx). – Harry Johnston Dec 23 '14 at 21:43
0

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.

Harry Johnston
  • 35,639
  • 6
  • 68
  • 158
  • Is it possible to call `CreateProcess` with `CREATE_SUSPENDED` and determine the path to the executable from the process handle? – Johnny 5 Dec 23 '14 at 22:06
  • Um ... maybe. You can get the path from a process handle using `GetModuleFileNameEx` but I'm not entirely certain whether that will work with a process that hasn't started running yet. – Harry Johnston Dec 23 '14 at 22:13