Directory.GetDirectories , Sort by name C# [duplicate]
Asked Answered
C

1

1

This one sounds duplicate, but all the solutions given is not satisfying one of the requirement that is sorting by name. for instance

J A1
J A2
J A3
J A10
J A11

The method returns J A1,J A10, J A11, J A2, J A3. But this is not expected as operating system sort them in a different way.

below solutions have tried already

var sorted = dirInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly).OrderBy(f => f.Name);

Array.Sort();
Charitacharitable answered 13/1, 2014 at 4:49 Comment(7)
15 second search: possible duplicate of C# How do I use Directory.GetFiles() to get files that have the same order as in Windows explorer? , #1013485Reest
Have you tried the implementation linked to here: https://mcmap.net/q/1772260/-how-would-i-sort-a-list-of-files-by-name-to-match-how-windows-explorer-displays-them ?Obscurity
@Obscurity no, Let me give a shot and updateCharitacharitable
@Obscurity That solved the sort issue ( NumericComparer nc = new NumericComparer(); Array.Sort(strDir, nc);) however applying this to Directoryinfo[] is bit complex.Charitacharitable
From what you've said, I'm not quite clear about what is solved and what isn't working. Can you update your question explaining the problem you're still having with the implementation you have now, with your current code? Without this, it's quite hard to help you further.Obscurity
@Obscurity posted answer myself.but credit goes to you.Charitacharitable
Glad you got it working. Never mind the credit, just happy to help! :)Obscurity
C
0

Thanks Baldrick for the valuable comment. using this ultimately solved the issue. there may be other ways but this is how I ended up.

 private void Walkdirectoryfulldepth(string dirPath, List<string> data)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(dirPath);
            var sorted = dirInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly).ToList();
            DirectoryInfo[] subDirs = dirInfo.GetDirectories("*.*", SearchOption.TopDirectoryOnly);
            string[] strDir=new string[subDirs.Count()];
            int i =0;
            foreach (var item in subDirs)
            {
                strDir[i] = item.FullName;
                i++;
            }
             NumericComparer nc = new NumericComparer();
             Array.Sort(strDir, nc);
             foreach (var item in strDir)
            {
                data.Add(Path.GetFileName(item));
                Walkdirectoryfulldepth(item, data);
            }
            //foreach (var item in subDirs)
            //    Walkdirectoryfulldepth(item.FullName, data);

        }

Get the below class from codeproject implemented similar to StrCmpLogicalW logical sorting in windows explorer API.

NumericComparer
StringLogicalComparer
Charitacharitable answered 13/1, 2014 at 6:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.