文件名排序
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApp1 { class Program { /* * 思路1:把文件名转换成int类型,字符串类型的替换掉,排好序后再 添加进来 */ public static string[] SortDirectoryFiles(string path) { string[] files = Directory.GetFiles(path); int[] intFiles = new int[files.Length]; string fileExtension = ""; //文件扩展名 //转换成int[] for (int i = 0; i < files.Length; i++) { fileExtension = Path.GetExtension(files[i]); intFiles[i] = Convert.ToInt32(files[i].Replace(path + "\\","").Replace(fileExtension,"")); } //int类型排序 Array.Sort(intFiles); //添加少的部分 string[] result = new string[files.Length]; for (int i = 0; i < files.Length; i++) { result[i] = intFiles[i] + fileExtension; } return result; } static void Main(string[] args) { string path = @"D:\Administrator\Images\安全员A证 2020-8-31\a\单选题\3"; string[] arr = SortDirectoryFiles(path); foreach (var item in arr) { Console.WriteLine(item); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string[] files = { "test1.jpg","test10.jpg","test2.jpg","test3.jpg","test20.jpg","test11.jpg","test5.jpg","test51.jpg" }; foreach (var item in files) { Console.WriteLine(item); } } } }
结果是这样的
test1.jpg
test10.jpg
test2.jpg
test3.jpg
test20.jpg
test11.jpg
test5.jpg
test51.jpg
我想这样的结果,按整数类型的排序结果
test1.jpg
test2.jpg
test3.jpg
test5.jpg
test10.jpg
test11.jpg
test20.jpg
test51.jpg