IMG-LOGO

List directories and subdirectories in ASP.Net C#.

andy - 09 Feb, 2014 3879 Views 0 Comment

You can use the following code function to display a list of directories including all subdirectories.

//Remember to import this namespace
using System.IO;

//This function will return a list of string and you have the option to recursive the subdirectories.
public List<string> ListDirectories(string path, bool recursive) {
    List<string> dirList = new List<string>();
    string[] dirInfo = null;
    string appPath = Server.MapPath(path);
    string tempDir = "";
    dirInfo = Directory.GetDirectories(appPath);
        

    if (dirInfo.Length > 0) {
        int index = 0;
        foreach (string dir in dirInfo) {
            if (dir.Length > appPath.Length) {
                try {
                    tempDir = dir.Substring(appPath.Length, dir.Length - appPath.Length);
                    dirList.Add(tempDir.Replace("\\", "/"));
                    if (recursive) {
                        ListSubDirectories(dir, path, dirList);
                    }
                } catch {
                }
            }
            index  = 1;
        }
    }

    return dirList;
}

public void ListSubDirectories(string fullPath, string relativePath, List<string> dirList) {
    string[] subdirInfo = null;
    subdirInfo = Directory.GetDirectories(fullPath);
    string folderDirectory = relativePath;
    string appPath = HttpContext.Current.Server.MapPath(folderDirectory);
    string tempDir = "";
    if (subdirInfo.Length > 0) {
        foreach (string subdir in subdirInfo) {
            if (subdir.Length > appPath.Length) {
                tempDir = subdir.Substring(appPath.Length, subdir.Length - appPath.Length);
                dirList.Add(tempDir.Replace("\\", "/"));
                ListSubDirectories(subdir, relativePath, dirList);
            }
        }
    }
}

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

How to remove html tags from string in c#?

Sometimes you need to remove HTML tags from string to ensure there are no dangerous or malicious scripts especially when you want to store the string or data text into the database.