InfernumDeus
InfernumDeus

Reputation: 1202

Correct way to check if some path refers to something inside specified folder

For example, I want to find out if specified directory path refers to Windows folder or anything inside it:

private static bool IsInsideWidowsFolder(string path)
{
    // windowsFolder = "C:\Windows"
    string windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

    if (path.Contains(windowsFolder)) returen true
    return false;
}

But this will also consider true other strings like:

C:\WindowsApp

Which class is able to consider that string invalid while considering following as true?

C:\Windows\system32

Upvotes: 1

Views: 95

Answers (3)

Mong Zhu
Mong Zhu

Reputation: 23732

you could just add a \ at the end of your windowsFolder path. This will mark the end of the word and allow you to match only the correct pattern: C:\Windows\

Looking closer at the problem actually the call :

string windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

returns C:\WINDOWS . But the Contains method is case sensitive. This would lead to a false match even with this path: C:\Windows\system32. You can use ToLower to make it case insensitive

if (path.ToLower().Contains(windowsFolder.ToLower() + "\\"))

another approach would be to parse the path up the parent hierarchy using Directory.GetParent and check each parent using the Equals method. It will allow you for a case insensitive comparison if you use the StringComparison.OrdinalIgnoreCase option

private static bool IsInsideWidowsFolder(string path)
{
    // windowsFolder = "C:\WINDOWS"
    string windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows);

    string parent = "";
    while ((parent = Directory.GetParent(path)?.FullName) != null)
    {
        if (windowsFolder.Equals(parent, StringComparison.OrdinalIgnoreCase))
        {
            return true;
        }
        path = parent;
    }

    return false;
}

Upvotes: 3

Jim Berg
Jim Berg

Reputation: 659

Append a backslash on windowsFolder

string windowsFolder = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + "\\";

You may also want to use a case insensitive method for checking such as:

return path.IndexOf(windowsFolder, StringComparison.OrdinalIgnoreCase)==0;

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81493

You can ensure both paths have backslashes

public static string EnsureBackSlash(this string input)
{
    return Path.GetFullPath(input)
        .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
        + Path.DirectorySeparatorChar;
}

Upvotes: 0

Related Questions