批量重命名工具用于统一修改文件夹下的文件名称(如添加前缀、替换关键词)。
案例:文件批量重命名
using System.IO; public class FileRenameTool { // 批量添加文件前缀 public static void AddPrefix(string folderPath, string prefix) { if (!Directory.Exists(folderPath)) { Console.WriteLine("文件夹不存在!"); return; } // 获取文件夹下的所有文件 string[] files = Directory.GetFiles(folderPath); int successCount = 0; foreach (string file in files) { try { string fileName = Path.GetFileName(file); string newFileName = prefix + fileName; string newFilePath = Path.Combine(folderPath, newFileName); // 避免覆盖已存在的文件 if (!File.Exists(newFilePath)) { File.Move(file, newFilePath); successCount++; Console.WriteLine($"重命名成功:{fileName} → {newFileName}"); } else { Console.WriteLine($"跳过:{newFileName} 已存在"); } } catch (Exception ex) { Console.WriteLine($"重命名失败({Path.GetFileName(file)}):{ex.Message}"); } } Console.WriteLine($"批量重命名完成!成功重命名 {successCount} 个文件"); } // 批量替换文件名中的关键词 public static void ReplaceKeyword(string folderPath, string oldKeyword, string newKeyword) { if (!Directory.Exists(folderPath)) { Console.WriteLine("文件夹不存在!"); return; } string[] files = Directory.GetFiles(folderPath); int successCount = 0; foreach (string file in files) { try { string fileName = Path.GetFileName(file); if (fileName.Contains(oldKeyword)) { string newFileName = fileName.Replace(oldKeyword, newKeyword); string newFilePath = Path.Combine(folderPath, newFileName); if (!File.Exists(newFilePath)) { File.Move(file, newFilePath); successCount++; Console.WriteLine($"重命名成功:{fileName} → {newFileName}"); } else { Console.WriteLine($"跳过:{newFileName} 已存在"); } } else { Console.WriteLine($"跳过:{fileName} 不包含关键词 {oldKeyword}"); } } catch (Exception ex) { Console.WriteLine($"重命名失败({Path.GetFileName(file)}):{ex.Message}"); } } Console.WriteLine($"批量替换完成!成功重命名 {successCount} 个文件"); } public static void Main(string[] args) { Console.WriteLine("=== 文件批量重命名工具 ==="); Console.Write("请输入文件夹路径:"); string folderPath = Console.ReadLine()?.Trim() ?? ""; Console.Write("请选择操作(1-添加前缀,2-替换关键词):"); string choice = Console.ReadLine()?.Trim() ?? ""; switch (choice) { case "1": Console.Write("请输入前缀:"); string prefix = Console.ReadLine()?.Trim() ?? ""; AddPrefix(folderPath, prefix); break; case "2": Console.Write("请输入要替换的关键词:"); string oldKeyword = Console.ReadLine()?.Trim() ?? ""; Console.Write("请输入替换后的关键词:"); string newKeyword = Console.ReadLine()?.Trim() ?? ""; ReplaceKeyword(folderPath, oldKeyword, newKeyword); break; default: Console.WriteLine("无效操作!"); break; } } }