How to get sub directories or sub folders in C#.Net | Asp.Net

By
Advertisement

Introduction:
In my previous article I have explained about How to create log files in C#.Net. In this article I am going to explain about how to get subdirectories or sub folders from a directory in C#.Net or ASP.Net.

Explanation:
The System.IO.Directory class is used for directory manipulation. This class provides static methods for creating, copying, moving, and deleting directories and subdirectories. To use this class we should import System.IO namespace first.

The GetDirectories method of the Directory class loads all the subdirectories of a subdirectory.

Below sample code gets all the subdirectories from the “RootFolder” and prints it in the form.
string rootPath = @"E:\RootFolder\";
string[] subdirs = Directory.GetDirectories(rootPath);
foreach (string subdirectory in subdirs)
{
    Response.Write(subdirectory+"<br/>");
}

To get the sub directories inside the subdirectory we can recursively call the function. Sample code is given below.
protected void Page_Load(object sender, EventArgs e)
{
    string rootPath = @"E:\RootFolder\";
    string[] subdirs = Directory.GetDirectories(rootPath);
    foreach (string subdirectory in subdirs)
    {
        PrintDirectories(subdirectory);
    }
}
private void PrintDirectories(string dir)
{
    string[] subdirs = Directory.GetDirectories(dir);
    foreach (string subdirectory in subdirs)
    {
        Response.Write(subdirectory + "<br/>");
    }
}

Do you like this article? Help us to improve. Please post your comments below.

0 comments:

Post a Comment

Online Casino