If I run a process with ShellExecute
(or in .net with System.Diagnostics.Process.Start()
) the filename process to start doesn't need to be a full path.
If I want to start notepad, I can use
Process.Start("notepad.exe");
instead of
Process.Start(@"c:\windows\system32\notepad.exe");
because the direcotry c:\windows\system32
is part of the PATH environment variable.
how can I check if a file exists on the PATH without executing the process and without parsing the PATH variable?
System.IO.File.Exists("notepad.exe"); // returns false (new System.IO.FileInfo("notepad.exe")).Exists; // returns false
but I need something like this:
System.IO.File.ExistsOnPath("notepad.exe"); // should return true
and
System.IO.File.GetFullPath("notepad.exe"); // (like unix which cmd) should return // c:\windows\system32\notepad.exe
Is there a predefined class to do this task available in the BCL?
The Windows System PATH tells your PC where it can find specific directories that contain executable files. ipconfig.exe , for example, is found in the C:\Windows\System32 directory, which is a part of the system PATH by default.
Get Executable Path With the Assembly Class in C#GetEntryAssembly() function is used to get the assembly of the currently executing code. We can get the path of the currently executing code with the Assembly. GetEntryAssembly(). Location property which returns the executable path of the current in a string variable.
Go to "My computer -> properties -> advanced -> environment variables -> Path" and edit path by adding .exe 's directory into path.
I think there's nothing built-in, but you could do something like this with System.IO.File.Exists:
public static bool ExistsOnPath(string fileName) { return GetFullPath(fileName) != null; } public static string GetFullPath(string fileName) { if (File.Exists(fileName)) return Path.GetFullPath(fileName); var values = Environment.GetEnvironmentVariable("PATH"); foreach (var path in values.Split(Path.PathSeparator)) { var fullPath = Path.Combine(path, fileName); if (File.Exists(fullPath)) return fullPath; } return null; }
This is risky, there's a lot more to it than just searching the directories in the PATH. Try this:
Process.Start("wordpad.exe");
The executable is stored in c:\Program Files\Windows NT\Accessories on my machine, that directory is not on the path.
The HKCR\Applications and HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths keys also play a role in finding executables. I'm fairly sure there are additional land-mines like this around, directory virtualization in 64-bit versions of Windows could trip you up for example.
To make this more reliable I think you need to pinvoke AssocQueryString(). Not sure, never had the need. The better approach is certainly to not have to ask the question.
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