检查可执行文件存在于Windows路径可执行文件、路径、Windows

2023-09-02 11:53:50 作者:再吵再闹不说分手

如果我运行与 ShellExecute的过程(或.NET与 System.Diagnostics.Process.Start())的文件名的过程开始并不需要是一个完整路径。

如果我要开始记事本,我可以使用

 的Process.Start(Notepad.exe的);
 
winRAR总是无法执行,而且运行起来都提示Windows无法访问指定设备路径或文件,您可能没有合适的权限访问这

而不是

 的Process.Start(@C: WINDOWS  SYSTEM32  NOTEPAD.EXE);
 

因为direcotry C: Windows System32下是PATH环境变量的一部分

我如何检查文件是否存在在PATH而不执行过程中,没有解析PATH变量?

  System.IO.File.Exists(Notepad.exe的); //返回false
(新System.IO.FileInfo(Notepad.exe的))的存在; //返回false
 

但我需要的东西是这样的:

  System.IO.File.ExistsOnPath(Notepad.exe的); //应返回true
 

  System.IO.File.GetFullPath(Notepad.exe的); //(如UNIX这CMD)应该返回
                                           // C: WINDOWS  SYSTEM32  NOTEPAD.EXE
 

有没有predefined类做这个任务的BCL可用?

解决方案

我觉得没有什么内置的,但你可以做这样的事情与System.IO.File.Exists:

 公共静态布尔ExistsOnPath(字符串文件名)
{
    如果(GetFullPath(文件名)!= NULL)
        返回true;
    返回false;
}

公共静态字符串GetFullPath(字符串文件名)
{
    如果(File.Exists(文件名))
        返回Path.GetFullPath(文件名);

    VAR值= Environment.GetEnvironmentVariable(PATH);
    的foreach(VAR路径values​​.Split(';'))
    {
        VAR FULLPATH = Path.Combine(路径,文件名);
        如果(File.Exists(FULLPATH))
            返回完整路径;
    }
    返回null;
}
 

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:windowssystem32notepad.exe");

because the direcotry c:windowssystem32 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:windowssystem32notepad.exe

Is there a predefined class to do this task available in the BCL?

解决方案

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)
{
    if (GetFullPath(fileName) != null)
        return true;
    return false;
}

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(';'))
    {
        var fullPath = Path.Combine(path, fileName);
        if (File.Exists(fullPath))
            return fullPath;
    }
    return null;
}