break

Reading folder names from a folder in C#

Another easy but useful task: Read the names of different folders that are inside a directory. Reading the names is easy, but splitting the absolute path of the directory to only get the name of the folder, is a little bit more interesting.

I am using ASP.NET to do this:

Default.aspx

<form id=”form1″ runat=”server”>
<asp:listbox id=”ListBox1″ runat=”server”></asp:listbox>
</form>

I just declare a listbox inside the form.

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string subDirectory in
System.IO.Directory.GetDirectories(
AppDomain.CurrentDomain.BaseDirectory))
{
// split the folders into an array of strings
string[] directory = subDirectory.Split(new char[] { '\\' });
// how many folders do we have?
int numOfDirectories = directory.Length;
// the last folder is the folder we are looking for
ListBox1.Items.Add(directory[numOfDirectories - 1]);
}
}
}

System.IO.Directory.GetDirectories as MSDN states: “Gets the names of subdirectories in the specified directory”. However, you get an absolute path of the directory.

If you would like to add the name of the folder to a listbox you will need to split the string that contains the different directories and store the directories in an array of strings:

string[] directory = subDirectory.Split(new char[] { ‘\\’ });

After this step, you get the amount of directories the absolute path has, and then look for the last directory in the array:

int numOfDirectories = directory.Length;
ListBox1.Items.Add(directory[numOfDirectories - 1]);

The directory I am using to read the files is AppDomain.CurrentDomain.BaseDirectory which is the base directory that the assembly resolver uses to search for assemblies.

The result of this snippet is:

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.

CAPTCHA Image
Reload Image