- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get all the directories and sub directories inside a path in C#?
To get the directories C# provides a method Directory.GetDirectories. The Directory.GetDirectories method returns the names of the subdirectories (including their paths) that match the specified search pattern in the specified directory, and optionally searches subdirectories.
In the below example * is matches Zero or more characters in that position. SearchOption TopDirectoryOnly .Gets only the top directories and SearchOption AllDirectories .Gets all the top directories and sub directories.
Note: The rootPath will be your systems rootPath so create a testfolder and use the rootPath accoridingly.
Example 1
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.TopDirectoryOnly); foreach (string dir in dirs) { Console.WriteLine (dir); } Console.ReadLine (); }
Output
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2
Example 2
static void Main (string[] args) { string rootPath = @"C:\Users\Koushik\Desktop\TestFolder"; string[] dirs = Directory.GetDirectories(rootPath, "*", SearchOption.AllDirectories); foreach (string dir in dirs) { Console.WriteLine (dir); } Console.ReadLine (); }
Output
C:\Users\Koushik\Desktop\TestFolder\TestFolderMain C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 1 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2 C:\Users\Koushik\Desktop\TestFolder\TestFolderMain 2\TestFolderMainSubDirectory
Advertisements