我要的是什麼樣的「的」命令:提供一個文件名(EXE,蝙蝠......),並返回該文件的完整路徑:路徑解析器在.NET
它的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 "";
}
是啊,謝謝。我們絕對可以自己寫一個,我們可以按照DLL搜索順序:http://msdn.microsoft.com/en-us/library/windows/desktop/ms682586(v=vs.85).aspx,但我很希望有一個在.NET框架第一:) –
最後,我寫了一個自己的建議... –