How to check if one path is a child of another path?

前端 未结 7 1471
温柔的废话
温柔的废话 2020-12-09 17:57

How to check if one path is a child of another path?
Just checking for substring is not a way to go, because there can items such as . and .., etc

7条回答
  •  一个人的身影
    2020-12-09 18:41

    I've used an extension method like this:

        /// 
        /// Check if a directory is the base of another
        /// 
        /// Candidate root
        /// Child folder
        public static bool IsBaseOf(this DirectoryInfo root, DirectoryInfo child)
        {
            var directoryPath = EndsWithSeparator(new Uri(child.FullName).AbsolutePath);
            var rootPath = EndsWithSeparator(new Uri(root.FullName).AbsolutePath);
            return directoryPath.StartsWith(rootPath, StringComparison.OrdinalIgnoreCase);
        }
    
        private static string EndsWithSeparator(string absolutePath)
        {
            return absolutePath?.TrimEnd('/','\\') + "/";
        }
    

提交回复
热议问题