简体   繁体   中英

how to read files in folder in ascending order?

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).

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

Habib's answer is correct, but note that you won't get the results in numerical order (ie 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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM