How to check whether 2 DirectoryInfo objects are pointing to the same directory?

前端 未结 5 2033
眼角桃花
眼角桃花 2020-12-10 14:11

I have 2 DirectoryInfo objects and want to check if they are pointing to the same directory. Besides comparing their Fullname, are there any other better ways

5条回答
  •  青春惊慌失措
    2020-12-10 14:21

    Some extension methods that I wrote for a recent project includes one that will do it:

        public static bool IsSame(this DirectoryInfo that, DirectoryInfo other)
        {
            // zip extension wouldn't work here because it truncates the longer 
            // enumerable, resulting in false positive
    
            var e1 = that.EnumeratePathDirectories().GetEnumerator();
            var e2 = other.EnumeratePathDirectories().GetEnumerator();
    
            while (true)
            {
                var m1 = e1.MoveNext();
                var m2 = e2.MoveNext();
                if (m1 != m2) return false; // not same length
                if (!m1) return true; // finished enumerating with no differences found
    
                if (!e1.Current.Name.Trim().Equals(e2.Current.Name.Trim(), StringComparison.InvariantCultureIgnoreCase))
                    return false; // current folder in paths differ
            }
        }
    
        public static IEnumerable EnumeratePathDirectories(this DirectoryInfo di)
        {
            var stack = new Stack();
    
            DirectoryInfo current = di;
    
            while (current != null)
            {
                stack.Push(current);
                current = current.Parent;
            }
    
            return stack;
        }
    
        // irrelevant for this question, but still useful:
    
        public static bool IsSame(this FileInfo that, FileInfo other)
        {
            return that.Name.Trim().Equals(other.Name.Trim(), StringComparison.InvariantCultureIgnoreCase) &&
                   that.Directory.IsSame(other.Directory);
        }
    
        public static IEnumerable EnumeratePathDirectories(this FileInfo fi)
        {
            return fi.Directory.EnumeratePathDirectories();
        }
    
        public static bool StartsWith(this FileInfo fi, DirectoryInfo directory)
        {
            return fi.Directory.StartsWith(directory);
        }
    
        public static bool StartsWith(this DirectoryInfo di, DirectoryInfo directory)
        {
            return di.EnumeratePathDirectories().Any(d => d.IsSame(directory));
        }
    

提交回复
热议问题