how to read files in folder in ascending order?

邮差的信 提交于 2019-12-08 19:51:38

问题


i have folder that contain image files which named with number 1,2,3...
how do i read the image file name in sequence starting with 1 until the end(whatever number it is).


回答1:


You may use OrderBy on file array.

DirectoryInfo dir = new DirectoryInfo(@"C:\yourfolder");
FileInfo[] files = dir.GetFiles();
//User Enumerable.OrderBy to sort the files array and get a new array of sorted files
FileInfo[] sortedFiles = files.OrderBy(r => r.Name).ToArray();

For File number with just numeric(int) names try:

FileInfo[] sortedFiles = files
                          .OrderBy(r => int.Parse(Path.GetFileNameWithoutExtension(r.Name)))
                          .ToArray();



回答2:


Habib's answer is correct, but note that you won't get the results in numerical order (i.e. you'll process 10.png before you process 2.png). To sort the filenames numerically, instead of alphabetically:

foreach (string fileName in Directory.GetFiles(Environment.CurrentDirectory)
         .OrderBy((f) => Int32.Parse(Path.GetFileNameWithoutExtension(f1))))
{
    // do something with filename
}



回答3:


Read all filenames into an array. Sort the array elements in ascending order. Done!




回答4:


Collect all the file names inside the directory using Arraylist and sort them (It also appicable for alpha numeric file names

        ArrayList <String> dirFiles=new ArrayList<String>();
        File file = new File("DirectoryPath");

        File createdFile = null;
        String [] str=file.list();
        for(int j=0;j<str.length;j++){
            dirFiles.add(str[j]);               
        }

        CustomComparator comparator = new CustomComparator();
        Collections.sort(dirFiles, comparator);
        for(String fileName: dirFiles){
                 Console.println(fileName);
         }


来源:https://stackoverflow.com/questions/12907499/how-to-read-files-in-folder-in-ascending-order

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