Search code examples
c#pathfile-exists

Is there a library method to see if a file exists that is cognizant of paths in the PATH environment variable


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);
}

Solution

  • 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

    1. SingleOrDefault, when there are multiple paths exists. (if you need only the first one you can replace it with FirstOrDefault).
    2. Path.Combine when the LINQ expression returns null. (you can check first by using if(paths.Any(f=>File.Exists(Path.Combine(f,fileName))) before assign to foundit variable.