C# - How to Search a Directory in the Given Directory?

Learn, how to search directory in a given directory (path) using C# program?
Submitted by IncludeHelp, on November 13, 2017 [Last updated : March 26, 2023]

Search a Directory in the Given Directory

To search a directory in the given directory in C#, we use Directory.GetDirectories() method.

Directory.GetDirectories()

This is a method of 'Directory' class, it returns list of matched sub-directories.

Syntax

String[] Directory. GetDirectories(string path, SearchOption);

Parameter(s)

  1. path - It is a location of directory.
  2. Search Option
    1. TopDirectoryOnly - Search only in current directory.
    2. AllDirectories - Search in all sub-directories also.

Return Value

This method returns the array of strings that contains matched sub-directories.

C# program to search a directory in the given directory

using System;
using System.IO;

namespace ConsoleApplication1 {
  class Program {
    static void Main() {
      //Search in current directory only.
      String[] dirs1 = Directory.GetDirectories("D:/Sample", "Green color", SearchOption.TopDirectoryOnly);

      if (dirs1.Length == 0) {
        Console.WriteLine("1.Directory Not Found");
      } else {
        Console.WriteLine("Sub directories are:");
        for (int i = 0; i < dirs1.Length; i++) {
          Console.WriteLine("\t" + dirs1[i]);
        }
      }

      //Search into all current directory .
      String[] dirs2 = Directory.GetDirectories("D:/Sample", "Green color", SearchOption.AllDirectories);

      if (dirs2.Length == 0) {
        Console.WriteLine("2.Directory Not Found");
      } else {
        Console.WriteLine("Sub directories are:");
        for (int i = 0; i < dirs2.Length; i++) {
          Console.WriteLine("\t" + dirs2[i]);
        }
      }
    }
  }
}

Output

1.Directory Not Found
Sub directories are:
        D:/Sample\dir1\Green color
        D:/Sample\dir2\Green color

Explanation

In the above program, we need to remember, when we use "Directory" class, System.IO namespace must be included in the program.

C#.Net Directory Class Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.