See if file path is inside a directory

前端 未结 2 886
后悔当初
后悔当初 2021-01-23 20:51

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(         


        
2条回答
  •  囚心锁ツ
    2021-01-23 21:09

    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);
    

提交回复
热议问题