如果我运行一个带ShellExecute的进程(或在带System.Diagnostics.Process.Start()的.Net中),启动的文件名进程不需要是完整路径.

如果我想启动记事本,我可以使用

Process.Start("notepad.exe");

而不是

Process.Start(@"c:\windows\system32\notepad.exe");

因为direcotry c:\windows\system32是PATH环境变量的一部分.

如何在不执行流程和不解析PATH变量的情况下判断路径上是否存在文件?

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:\windows\system32\notepad.exe

BCL中是否有用于执行此任务的预定义类?

推荐答案

我觉得里面没有内置的东西,但是你可以用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;
}

.net相关问答推荐

使用PowerShell在Windows容器内安装exe

为什么.Net 8.0.100是预览版?

使用托管身份而不是检测密钥配置Application Insights

在 .NET 7 项目上设置 Sentry 时遇到问题

在 Invoke() 中运行时,跨线程操作对表单控件无效 - .NET

仅在有换行符时捕获分隔符之间的所有文本

什么是表达式树,如何使用它们,为什么要使用它们?

C#6.0 字符串插值本地化

是否可以模拟 .NET HttpWebResponse?

Style 和 ControlTemplate 的区别

XmlNode 值与内部文本

使用多个 MemoryCache 实例

注册 COM 互操作与使程序集 COM 可见

如何从字符串中删除所有字母字符?

如果需要,将方案添加到 URL

覆盖 ASP.NET MVC 中的授权属性

使用+运算符的字符串连接

绑定到不在列表中的值的可编辑组合框

如何在安装后立即启动 .NET Windows 服务?

LINQ 可以与 IEnumerable 一起使用吗?