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

前端 未结 7 1418
温柔的废话
温柔的废话 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:

        /// <summary>
        /// Check if a directory is the base of another
        /// </summary>
        /// <param name="root">Candidate root</param>
        /// <param name="child">Child folder</param>
        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('/','\\') + "/";
        }
    
    0 讨论(0)
提交回复
热议问题