How to list only the name of existing folders in a given directory

Asked

Viewed 589 times

0

How can I list only the name of a folder that is inside a root folder?

Example:

Pasta raiz C:/Downloads

SubPastas: Teste/ Teste 2

Mostrando pastas

In my DLL I can list the folders but with its full path, I would just like to list the name of the subfolders:

In case only Teste and Teste 2

Follows code:

 private void carregarFolders()
    {
        try
        {
            string caminho = @"C:/Downloads";
            ddlFolders.DataSource = Directory.GetDirectories(caminho);
            ddlFolders.DataValueField = "";
            ddlFolders.DataTextField = "";
            ddlFolders.DataBind();
            ddlFolders.Items.Insert(0, new ListItem(string.Empty, string.Empty));


        }
        catch (Exception ex)
        {

            throw ex;
        }
    }

Resultado na tela

2 answers

3

The form that will give you better performance:

try {
    var dirs = new List<string();
    foreach (var dir in Directory.EnumerateDirectories(caminho)) dirs.Add(dir.Substring(dir.LastIndexOf("\\") + 1));
} catch (UnauthorizedAccessException ex) {
    //faça algo útil aqui ou retire esse catch
} catch (PathTooLongException ex) {
    //faça algo útil aqui ou retire esse catch
}
ddlFolders.DataSource = dirs;

I put in the Github for future reference.

Never catch an exception to do anything, especially to launch it again.

2


It is possible, using LINQ, to map each complete path to an instance of DirectoryInfo and, from this instance, get only the "final name" of the directory using the property Name.

var source = Directory.GetDirectories(caminho)
                      .Select(c => new DirectoryInfo(c).Name)
                      .ToList();

ddlFolders.DataSource = source;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.