Check if a folder is a direct sub folder of a main folder. - CSharp File IO

CSharp examples for File IO:Directory

Description

Check if a folder is a direct sub folder of a main folder.

Demo Code


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

public class Main{
        /// <summary>
        /// Check if a folder is a direct sub folder of a main folder.
        /// True is only returned if this is a direct sub folder, not if
        /// it is some sub folder few levels below.
        /// </summary>
        static public bool IsDirectSubfolder(string subfolder, string mainFolder)
        {
            // First check if subFolder is really a sub folder of mainFolder
            if (subfolder != null &&
                subfolder.StartsWith(mainFolder))
            {
                // Same order?
                if (subfolder.Length < mainFolder.Length + 1)
                    // Then it ain't a sub folder!
                    return false;
                // Ok, now check if this is direct sub folder or some sub folder
                // of mainFolder sub folder
                string folder = subfolder.Remove(0, mainFolder.Length + 1);
                // Check if this is really a direct sub folder
                for (int i = 0; i < folder.Length; i++)
                    if (folder[i] == '\\')
                        // No, this is a sub folder of mainFolder sub folder
                        return false;
                // Ok, this is a direct sub folder of mainFolder!
                return true;
            } // if (subFolder)
            // Not even any sub folder!
            return false;
        } // IsDirectSubFolder(subFolder, mainFolder)
}

Related Tutorials