Juan
Juan

Reputation: 15725

See if file path is inside a directory

How can I check whether a path to a file that doesn't necessarily exists points to a location inside a particular directory? Say I have a method:

bool IsInside(string path, string folder)
{
    //...
}

Then, if I call it like:

IsInside("C:\\Users\\Dude\\Hi", "C:\\Users\\Dude\\Hi\\SubFolder\\SubSubFolder\\tile.txt")

should return true (note the sub folder), but if I call it like:

IsInside("C:\\Users\\Dude\\Hi", "C:\\Users\\Dude\\BadFolder\\SubFolder\\SubSubFolder\\tile.txt")

should return false. The only thing I can think of right now is using string's StartsWith, but sounds kinda hacky to me. I haven't found a native .NET method that would check this either.

Upvotes: 1

Views: 1616

Answers (2)

Mark Hall
Mark Hall

Reputation: 54562

You could try the string.IndexOf method. If you use the overload with the StringComparison enumeration it should give you the result you need.

From above link:

Reports the zero-based index of the first occurrence of one or more characters, or the first occurrence of a string, within this string. The method returns -1 if the character or string is not found in this instance.

bool IsInside(string folder, string path)
{
   if (path.IndexOf(folder,StringComparison.OrdinalIgnoreCase) != -1)
        return true;
    else
        return false;    

Upvotes: 2

Glen Hughes
Glen Hughes

Reputation: 4832

Do you need to handle relative paths (../../someFile.txt)? Something like this would work:

private bool IsInside(DirectoryInfo path, DirectoryInfo folder)
{
    if (path.Parent == null)
    {
        return false;
    }

    if (String.Equals(path.Parent.FullName, folder.FullName, StringComparison.InvariantCultureIgnoreCase))
    {
        return true;
    }

    return IsInside(path.Parent, folder);
}

Then call it like this:

DirectoryInfo folder = new DirectoryInfo("C:\\Users\\Dude\\Hi");
DirectoryInfo path = new DirectoryInfo("C:\\Users\\Dude\\Hi\\SubFolder\\SubSubFolder\\tile.txt");

bool result = IsInside(path, folder);

Upvotes: 3

Related Questions