Craig Gidney
Craig Gidney

Reputation: 18276

Is there a method to determine if a file path is nested within a directory path in .Net

I want to determine if a folder contains a file, when both are specified by a path.

At first glance this seems simple. Just check if the file path starts with the directory path. However, this naive check ignores several issues:

Is there an existing method in the framework, or do I have to write my own?

Upvotes: 2

Views: 314

Answers (2)

Wade Tandy
Wade Tandy

Reputation: 4144

As far as I know, there is no built-in .NET method to do this, but the following function should accomplish this using the FileInfo and DirectoryInfo classes:

public static bool FolderContainsFile(String folder, String file)
{
    //Create FileInfo and DirectoryInfo objects
    FileInfo fileInfo = new FileInfo(file);
    DirectoryInfo dirInfo = new DirectoryInfo(folder);

    DirectoryInfo currentDirectory = fileInfo.Directory;
    if (dirInfo.Equals(currentDirectory))
        return true;

    while (currentDirectory.Parent != null)
    {
        currentDirectory = currentDirectory.Parent;

        if(currentDirectory.Equals(dirInfo)
            return true;
    }

    return false;

}

Upvotes: 1

Hans Olsson
Hans Olsson

Reputation: 55009

I'm not sure if it'll work in all cases, but I'd suggest looking at Path.GetFullPath.

Quote: Returns the absolute path for the specified path string.

Upvotes: 1

Related Questions