如果我运行与 ShellExecute的过程
(或.NET与 System.Diagnostics.Process.Start()
)的文件名的过程开始并不需要是一个完整路径。
如果我要开始记事本,我可以使用
的Process.Start(Notepad.exe的);
而不是
的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;
}
上一篇:我怎样才能测试负零?测试
下一篇:检查SQL表存在存在、SQL