相信对很多朋友将对文件进行更名操作并不陌生,修改的方法也非常的简单,但是,如果需要同时修改多个文件的名称,那实现起来就会非常的麻烦,所以,我们该如何通过c#编程语言编写源代码实现批量更改文件名称功能呢?下面,济南网站建设小编news.hcsw666.com/就来与大家一起解决类似的需求,有兴趣的朋友可以过来参考一下。
关键代码:
class Program { static void Main() { string folderPath = @"C:\Your\Folder\Path"; // 替换为你的目标文件夹路径 string prefix = "prefix_"; // 要添加的前缀 try { // 获取指定目录下所有的 .txt 文件 string[] files = Directory.GetFiles(folderPath, "*.txt"); foreach (string file in files) { // 获取文件名(不含路径) string oldFileName = Path.GetFileName(file); // 构造新文件名 string newFileName = prefix + oldFileName; // 拼接完整的新路径 string newFilePath = Path.Combine(folderPath, newFileName); // 重命名文件 File.Move(file, newFilePath); Console.WriteLine($"已重命名: {oldFileName} -> {newFileName}"); } Console.WriteLine("批量重命名完成!"); } catch (Exception ex) { Console.WriteLine("发生错误:" + ex.Message); } } }
评论