Given full path, check if path is subdirectory of some other path, or otherwise

前端 未结 9 1373
难免孤独
难免孤独 2020-12-03 13:22

I have 2 strings - dir1 and dir2, and I need to check if one is sub-directory for other. I tried to go with Contains method:

dir1.contains(dir2);
         


        
9条回答
  •  盖世英雄少女心
    2020-12-03 13:57

    string path1 = "C:\test";
    string path2 = "C:\test\abc";
    
    var root = Path.GetFullPath(path1);
    var secondDir = Path.GetFullPath(path2 + Path.AltDirectorySeparatorChar);
    
    if (!secondDir.StartsWith(root))
    {
    }
    

    Path.GetFullPath works great with paths, like: C:\test\..\forbidden\

提交回复
热议问题