简体   繁体   中英

Equivalent of “where” command prompt command in C#

Is there any way to find a path in C# dynamically without executing "where" command prompt command?

For example, if I want to find mspaint exe, I can type this in command prompt

where mspaint

and it returns the path.

I don't think there is a built-in method in the Common Language Runtime to do this for you, but you can certainly do it yourself:

  • Get the value of the PATH environment variable
  • Split it on ; delimiters to get a list of directories in the path
  • Check each of those directories to see if it contains program

Example:

public static string FindInPath(string filename)
{
    var path = Environment.GetEnvironmentVariable("PATH");
    var directories = path.Split(';');

    foreach (var dir in directories)
    {
        var fullpath = Path.Combine(dir, filename);
        if (File.Exists(fullpath)) return fullpath;
    }

    // filename does not exist in path
    return null;
}

Don't forget to add .exe to the filename. (Or, you could modify the code above to search for any executable extension: .bat , .com , .exe ; or perhaps even any extension at all.)

This is based on @TypeIA's answer, but it supports the current directory and all PATHEXT .

public static string Where(string file)
{
    var paths = Environment.GetEnvironmentVariable("PATH").Split(';');
    var extensions = Environment.GetEnvironmentVariable("PATHEXT").Split(';');
    return (from p in new[] { Environment.CurrentDirectory }.Concat(paths)
            from e in new[] { string.Empty }.Concat(extensions)
            let path = Path.Combine(p.Trim(), file + e.ToLower())
            where File.Exists(path)
            select path).FirstOrDefault();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM