Question

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();
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top