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

1

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

Example:

Pasta raiz C:/Downloads

SubPastas: Teste/ Teste 2

InmyDLLIcanlistthefoldershoweverwiththeirfullpath,Iwouldjustliketolistthenameofthesubfolders:

IncaseonlyTesteandTeste2

Followthecodebelow:

privatevoidcarregarFolders(){try{stringcaminho=@"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;
        }
    }

    
asked by anonymous 08.05.2018 / 16:24

2 answers

2

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

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

ddlFolders.DataSource = source;
    
08.05.2018 / 16:39
3

The form that will give you the best 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;

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

    
08.05.2018 / 16:39