问题
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