C# 文件排序:按名称对文件进行排序并移动 - 代码示例
在 C# 中,可以使用以下方法对文件进行排序:\n\n1. 使用 Directory 类 的 GetFiles 方法获取指定目录下的所有文件:\ncsharp\nstring[] files = Directory.GetFiles(directoryPath);\n\n\n2. 使用 Array 类 的 Sort 方法对文件数组进行排序:\ncsharp\nArray.Sort(files);\n\n\n3. 使用 File 类 的 Move 方法将排序后的文件移动到新的位置:\ncsharp\nfor (int i = 0; i < files.Length; i++)\n{\n string newFilePath = Path.Combine(newDirectoryPath, $"file{i + 1}.txt");\n File.Move(files[i], newFilePath);\n}\n\n\n完整示例代码如下:\ncsharp\nusing System;\nusing System.IO;\n\nclass Program\n{\n static void Main()\n {\n string directoryPath = "C:\Files";\n string newDirectoryPath = "C:\SortedFiles";\n\n string[] files = Directory.GetFiles(directoryPath);\n\n Array.Sort(files);\n\n for (int i = 0; i < files.Length; i++)\n {\n string newFilePath = Path.Combine(newDirectoryPath, $"file{i + 1}.txt");\n File.Move(files[i], newFilePath);\n }\n }\n}\n\n\n请确保将 directoryPath 和 newDirectoryPath 变量的值替换为实际的目录路径。此示例假定文件扩展名为 .txt,并将排序后的文件命名为 file1.txt,file2.txt 等。
原文地址: https://www.cveoy.top/t/topic/pFZz 著作权归作者所有。请勿转载和采集!