Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through directory and only return folder names through a web method using C#? [duplicate]

Tags:

c#

webmethod

I'm trying to read a directory using C# and return all the folder names in that directory. I do not want any nested folders or files to be returned, only the immediate folders in the directory.

I'm going to use these names to build a side nav in my application. Users will have the ability to create new folders so I want the nav to be dynamically built as new folders get created over time. I have tried to different solutions thus far.

1st - I used Directory.GetFiles() and looped through directory but this returns every single folder and file name found in the whole directory.

2nd - I used Directory.GetDirectory() and tried looping through the directory and this does return just the folder name, but only the first folder! I need the remaining folders. It's like my loop is not working.

1st Try:

 string [] files = Directory.GetFiles(@"\\\\SERVERNAME\\Data\\ServerLinks\\Safety\\","*",SearchOption.AllDirectories); 
    string File = "";
    for (int ii = 0; ii < files.Length; ii++)
    {
        File += "|" + files[ii];
    }
    return (File);

2nd Try:

string path = @"\\\\SERVERNAME\\Data\\ServerLinks\\Safety\\";
    foreach (string folder in Directory.GetDirectories(path))
    {
        string name = folder.Remove(0, folder.LastIndexOf('\\') + 1);
        return (name);            
    }
    return ("");
like image 387
ChisumTrail Avatar asked Apr 13 '26 15:04

ChisumTrail


1 Answers

Your second attempt is in the correct direction. You are just returning on the first folder. Instead you should store all the folders and return the collection. Or just do a yield return to return as an IEnumerable

var allFolders = new List<string>();
string path = @"\\SERVERNAME\Data\ServerLinks\Safety\";
foreach (string folder in Directory.GetDirectories(path)) {
    string name = folder.Remove(0, folder.LastIndexOf('\\') + 1);
    allFolders.Add(name)
}
return allFolders;

If I were you, I would use a slightly different code which is lot more robust and idiomatic

new DirectoryInfo(path).GetDirectories().Select(d => d.Name);

Instead of using the Directory class and then doing path manipulations using string functions, you can keep information as a Directory object with new DirectoryInfo(path).GetDirectories(). I have just done a select on the DirectoryInfo.Name, since that's what your code was showing, but you have a more powerful DirectoryInfo object available at your disposal with this way

like image 85
Vikhram Avatar answered Apr 15 '26 06:04

Vikhram