public static string FindFilePath(string file, string localPath)
{
file = Environment.ExpandEnvironmentVariables(file);
if (!File.Exists(file))
{
if (Path.GetDirectoryName(file) == String.Empty)
{
foreach (string test in (Environment.GetEnvironmentVariable("PATH") ?? "").Split(';'))
{
string path = test.Trim();
if (!string.IsNullOrEmpty(path) && File.Exists(path = Path.Combine(path, file)))
return Path.GetFullPath(path);
}
}
file = Path.Combine(localPath, file);
if (File.Exists(file)) return file;
return $"[{ Path.GetFileName(file) }] not found.";
}
return Path.GetFullPath(file);
}
调用示例
var filePath = FindFilePath("Cmd.exe", "");
http://csharptest.net/526/how-to-search-the-environments-path-for-an-exe-or-dll/index.html