How to check if directory 1 is a subdirectory of dir2 and vice versa

后端 未结 11 1674
北海茫月
北海茫月 2020-12-31 04:07

What is an easy way to check if directory 1 is a subdirectory of directory 2 and vice versa?

I checked the Path and DirectoryInfo helperclasses but found no system-r

11条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-31 04:17

    With help from the great test cases written in angularsen's answer, I wrote the following simpler extension method on .NET Core 3.1 for Windows:

    public static bool IsSubPathOf(this string dirPath, string baseDirPath)
    {
        dirPath = dirPath.Replace('/', '\\');
        if (!dirPath.EndsWith('\\'))
        {
            dirPath += '\\';
        }
    
        baseDirPath = baseDirPath.Replace('/', '\\');
        if (!baseDirPath.EndsWith('\\'))
        {
            baseDirPath += '\\';
        }
    
        var dirPathUri = new Uri(dirPath).LocalPath;
        var baseDirUri = new Uri(baseDirPath).LocalPath;
    
        return dirPathUri.Contains(baseDirUri, StringComparison.OrdinalIgnoreCase);
    }
    

提交回复
热议问题