I have the code below. It works OK but I'm wondering if there is a less verbose way to do it. Is there a library method to see if a file exists that is cognizant of paths in the PATH environment variable such that I can do something like if (FileExistsInAnyPath("robocopy.exe")
without having to extract all the paths from PATH
string foundIt = "";
string[] paths = (Environment.GetEnvironmentVariable("Path")).Split(';');
foreach (string path in paths)
{
if (File.Exists((path + "\\robocopy.exe")))
{
foundIt = (path + "\\robocopy.exe");
break;
}
}
if (!string.IsNullOrEmpty(foundIt))
{
// do something with fq path name
Console.WriteLine("found it here: " + foundIt);
}
I think Linq will help you by (using System.Linq)
var paths = (Environment.GetEnvironmentVariable("Path")).Split(';');
var fileName = "robocopy.exe";
var foundit = Path.Combine(paths.SingleOrDefault(f=>File.Exists(Path.Combine(f,fileName))),fileName);
Also, you can wrap that code on your own method FileExistsInAnyPath(string fileName)
but here you need to handle expected exceptions