我想要的是“which”命令:提供文件名(exe,bat ...)并返回该文件的完整路径:
哪个java.exe
C:\ Windows \ System32下\ java.exe的
代码如下:
string fileName = "java.exe"
string fullPath = PathResolver.Resolve(fileName);
我们在.NET框架中有这样的功能吗?
感谢。
更新
最后,我自己写了一篇:
// Reoslve the full path of a file name
// fileName: of absolute path or relative path; with ext or without ext
static string ResolvePath(string fileName)
{
// 0. absolute path
string[] stdExts = { ".bat", ".cmd", ".pl", ".exe" };
if (Path.IsPathRooted(fileName))
{
if (File.Exists(fileName))
{
return fileName;
}
else
{
foreach (string eachExt in stdExts)
{
string fullPath = fileName + eachExt;
if (File.Exists(fullPath))
{
return fullPath;
}
}
}
return "";
}
// 1. candidate extensions
string fileNameNoExt = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
string[] candidateExts;
if (string.IsNullOrEmpty(ext))
{
candidateExts = stdExts;
}
else
{
string[] exts = { ext };
candidateExts = exts;
}
// 2. candidate path:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx#search_order_for_desktop_applications
List<string> candidatePaths = new List<string>();
// application dir
string fileApp = Process.GetCurrentProcess().MainModule.FileName;
candidatePaths.Add(Path.GetDirectoryName(fileApp));
// current dir
candidatePaths.Add(Directory.GetCurrentDirectory());
// system dir
candidatePaths.Add(Environment.SystemDirectory);
// windows dir
string winDir = Environment.GetEnvironmentVariable("windir");
candidatePaths.Add(winDir);
// PATH
string[] paths = Environment.GetEnvironmentVariable("PATH").Split(';');
foreach (string path in paths)
{
// strip the trailing '\'
candidatePaths.Add(Path.GetDirectoryName(path));
}
// 3. resolve
foreach (string eachPath in candidatePaths)
{
foreach (string eachExt in candidateExts)
{
string fullPath = eachPath + "\\" + fileNameNoExt + eachExt;
if (File.Exists(fullPath))
return fullPath;
}
}
return "";
}
答案 0 :(得分:2)
我不知道这是否可以帮到你:
public string PathResolver(string filename)
{
string[] paths = Environment.GetEnvironmentVariable("PATH").Split(';');
foreach (string path in paths)
{
string fname = Path.Combine(path, filename);
if (File.Exists(filename)) return fname;
}
return "";
}
答案 1 :(得分:1)
你应该看看这个在NDepend和其他项目中使用的免费库,
答案 2 :(得分:0)
我不确定&#34;哪个&#34;命令,但.net有
Type.GetTypeFromProgID("java.exe")
http://msdn.microsoft.com/en-us/library/system.type.gettypefromprogid.aspx
我不确定从哪里开始,但也许有帮助...
答案 3 :(得分:0)
查看FileInfo
类的FullName
property。
FileInfo fi = new FileInfo("foo.exe");
string fullanme = fi.FullName;
答案 4 :(得分:0)
我可以建议一种方法来查找可执行文件的完整路径,只需使用文件名实际运行它(可能不是你想要的):
Process p = new Process();
p.StartInfo = new ProcessStartInfo("notepad.exe");
p.Start();
Console.WriteLine(p.MainModule.FileName);