HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Check if a file exists in a directory or parent

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
directoryfileparentexistscheck

Problem

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.

Solution

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 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 => File.Exists(x));
}

var actualFileName = FindFile(fileName);

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

Code Snippets

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

var fileExists = 
    File.Exists(fileName) ||
    File.Exists(
        Path.Combine(
            Directory.GetParent(Path.GetDirectoryName(fileName)).FullName,
            Path.GetFileName(fileName)
        )
    );
static IEnumerable<string> 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);
}
if(FileExists(fileName)) ...
static string FindFile(this string fileName) 
{
    return GetFileSearchPaths(fileName).FirstOrDefault(x => File.Exists(x));
}

var actualFileName = FindFile(fileName);

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

Context

StackExchange Code Review Q#133821, answer score: 6

Revisions (0)

No revisions yet.