Search code examples
c#.netdirectoryinfo

C# Directory.GetFolder Order Folders And Set Them To List<> Without Losing Memory And Doing Additional Sort Operations


just want know how to Order folders like they looking in my Explorer folder Sorted by name .. It's looks like :::

enter image description here

So i tried use this :::

 DirectoryInfo sourcreInfo = new DirectoryInfo(SourcePath);
                DirectoryInfo[] sourceFolders = sourcreInfo.GetDirectories().OrderBy(p => p.Name).ToArray();

but for sure it's not working ... not sorting and in addition it needs addition memmory ... imagine i have in my folder 1000 reports ...

soo ... here how i worked with this sourceFolders:: reportDir is just List

  foreach (DirectoryInfo report in sourceFolders)
                {
                  reportDir.Add(Path.GetFileNameWithoutExtension(report.Name)).ToString()));      
                }

Guys waiting for any proposition how to get Ordered by Name Directories ... To make this operation correctly .. :)

Really what in result i getting using DirectoryInfo ::::

enter image description here

I expected :: report1, report2 , report3 , report4 , report5 ....

by numbers, like shows in explorer picture


Solution

  • Try with EnumerateDirectories, like this:

    DirectoryInfo di = new DirectoryInfo("c:\\windows");
    List<DirectoryInfo> subDirs = di.EnumerateDirectories().OrderBy(d => d.Name).ToList();
    

    EDIT: Ordering works and it will be like in your example, only a bit more efficient by using EnumerateDirectories. Ordering is done as text, not as numbers, so report2 will always be after report1 and report11119. So, if you want it to be ordered correctly, have it with leading zeros, like report01, report02...

    To order by number, you'll have to do some tinkering like this:

    Order by taking 6th letter from report name, convert it to integer and then sort. In this case, you'll get exception if folder name is shorter than seven chars, if seventh or any following char isn't number (like in cases of folder names like rep1, reports1, reporting etc)

    DirectoryInfo di = new DirectoryInfo("c:\\temp\\reports");
    List<DirectoryInfo> subDirs = 
        di.EnumerateDirectories()
            .OrderBy(d => int.Parse(d.Name.Substring(6))).ToList();