C#实现批量修改文件夹部分名称
环境:.NET FrameWork 4.8
应用:控制台应用
额外引用:using System.IO;
核心代码:
// 目标文件夹路径
string folderPath = @"D:\Project\MyPro\Base";
// 原始前缀和目标前缀
string oldPrefix = "Base_";
string newPrefix = "Post_";
try
{
// 获取文件夹中所有符合条件的.cs文件
string[] files = Directory.GetFiles(folderPath, $"{oldPrefix}*.cs");
if (files.Length == 0)
{
Console.WriteLine("未找到需要修改的文件");
return;
}
foreach (string filePath in files)
{
// 获取文件名(不含路径)
string fileName = Path.GetFileName(filePath);
// 生成新文件名(替换前缀)
string newFileName = fileName.Replace(oldPrefix, newPrefix);
// 生成新文件的完整路径
string newFilePath = Path.Combine(Path.GetDirectoryName(filePath), newFileName);
// 执行重命名
File.Move(filePath, newFilePath);
Console.WriteLine($"已修改: {fileName} -> {newFileName}");
}
Console.WriteLine($"批量修改完成,共处理 {files.Length} 个文件");
}
catch (Exception ex)
{
Console.WriteLine($"操作出错: {ex.Message}");
}