1

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
InfernumDeus
  • 1,185
  • 1
  • 11
  • 33

3 Answers3

3

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;
}
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
0

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;
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
0

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;
Jim Berg
  • 609
  • 4
  • 7
  • Mong Zhu's answer is more complete, but instead of using Directory.GetParent you should use Path.GetDirectoryName. Directory will actually use the file system to figure out the parent directory (disk reads involved) while Path will just parse the path string which will be more efficient. – Jim Berg Jan 29 '18 at 08:18