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.
Typing cd \ will move you from any folder on the drive to the root folder of that drive. If you're in C:\Windows\System32 , type cd \ and press Enter to move to C:\ . If the path has spaces, enclose it in double-quotes.
The where command is a Windows which equivalent in a command-line prompt (CMD). In a Windows PowerShell the alternative for the which command is the Get-Command utility.
The path command specifies the location where MS-DOS should look when it executes a command. For example, if you were to use the "format" command, the path must be specified, or you will receive the message "bad command or file name." See our path definition for a full explanation and examples of paths on computers.
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:
PATH
environment variable;
delimiters to get a list of directories in the pathprogram
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With