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

ε祈祈猫儿з 提交于 2019-12-13 00:36:48

问题


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();

回答1:


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


来源:https://stackoverflow.com/questions/21084096/directory-getdirectories-sort-by-name-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!