Check if a file exists in a directory or parent I want to check if a file exists in a given directory or in the parent one, so I wrote this code:

if (File.Exists(fileName) || 
    File.Exists(Directory.GetParent(Path.GetDirectoryName(fileName)).FullName +
        Path.DirectorySeperatorChar + 
        Path.GetFileName(fileName)))


However, this seems quite odd to me and I wonder if there is a smarter approach to making this check. I'm not necessarily looking for a shorter approach, but a more understandable one.
It's safer to use the Path.Combine method for joining the directory name and file name:

var fileName = @"c:\temp\foo.txt";

var fileExists = 
    File.Exists(fileName) ||
    File.Exists(
        Path.Combine(
            Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
            Path.GetFileName(fileName)
        )
    );


What else you could to is to take it out of the if and use a helper variable and add some identation.



Another approach could be to encapsulate the search paths and the file exists check:

static IEnumerable&lt;string&gt; GetFileSearchPaths(string fileName)
{
    yield return fileName;
    yield return Path.Combine(
        Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
        Path.GetFileName(fileName)
    );
}

// or as an extension
static bool FileExists(string fileName) 
{
    return GetFileSearchPaths(fileName).Any(File.Exists);
}


Usage:

if(FileExists(fileName)) ...


or you can get the actual file name from the search:

static string FindFile(this string fileName) 
{
    return GetFileSearchPaths(fileName).FirstOrDefault(x =&gt; File.Exists(x));
}

var actualFileName = FindFile(fileName);

if (!string.IsNullOrEmpty(actualFileName)) ...