Returns true when child Folder is a sub folder of parent Folder - CSharp File IO

CSharp examples for File IO:Directory

Description

Returns true when child Folder is a sub folder of parent Folder

Demo Code


using System.Text;
using System.Linq;
using System.IO;//from  ww w  .  j  av  a 2s.  co m
using System.Collections.Generic;
using System.Collections;
using System;

public class Main{
        /// <summary>
        /// Returns true when childFolder is a subfolder of parentFolder
        /// </summary>
        /// <param name="childFolder"></param>
        /// <param name="parentFolder"></param>
        /// <returns></returns>
        public static bool IsChildFolder(DirectoryInfo childFolder, DirectoryInfo parentFolder)
        {
            if (childFolder.Parent == null)
                return false;
            childFolder = childFolder.Parent;

            if (childFolder.IsSameDirectory(parentFolder))
                return true;

            return IsChildFolder(childFolder, parentFolder);
        }
        static public bool IsSameDirectory(this DirectoryInfo info, DirectoryInfo other)
        {
            return (
                0 == String.Compare(
                    System.IO.Path.GetFullPath(info.FullName).TrimEnd('\\'),
                    System.IO.Path.GetFullPath(other.FullName).TrimEnd('\\'),
                    StringComparison.InvariantCultureIgnoreCase))
                ;
        }
}

Related Tutorials