检查 Windows 路径中是否存在可执行文件 [英] Check if an executable exists in the Windows path
问题描述
如果我使用 ShellExecute
(或在 .net 中使用 System.Diagnostics.Process.Start()
)运行进程,则启动的文件名进程不需要是一个完整的路径.
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");
代替
Process.Start(@"c:windowssystem32
otepad.exe");
因为目录 c:windowssystem32
是 PATH 环境变量的一部分.
because the direcotry c:windowssystem32
is part of the PATH environment variable.
如何在不执行进程和解析 PATH 变量的情况下检查 PATH 上是否存在文件?
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
但我需要这样的东西:
System.IO.File.ExistsOnPath("notepad.exe"); // should return true
和
System.IO.File.GetFullPath("notepad.exe"); // (like unix which cmd) should return
// c:windowssystem32
otepad.exe
BCL 中是否有预定义的类来执行此任务?
Is there a predefined class to do this task available in the BCL?
推荐答案
我认为没有什么内置的,但你可以用 System.IO.File.Exists:
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;
}
这篇关于检查 Windows 路径中是否存在可执行文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!