如何删除文件夹内指定图片后重命名后续图片?
批量重命名后续图片的实现方案
你可以在删除指定图片后,通过循环遍历后续的图片文件,依次将它们重命名为序号减1的文件名,完整代码如下:
using System.IO; // 要删除的图片序号 int deleteIndex = 3; string folderPath = @"C:\images"; // 1. 删除指定图片 string deleteFilePath = Path.Combine(folderPath, $"img{deleteIndex}.jpg"); if (File.Exists(deleteFilePath)) { File.Delete(deleteFilePath); } // 2. 重命名后续图片 int currentIndex = deleteIndex + 1; while (true) { string oldFilePath = Path.Combine(folderPath, $"img{currentIndex}.jpg"); if (!File.Exists(oldFilePath)) { // 找不到下一个文件,结束循环 break; } // 新文件名的序号是当前序号减1 string newFilePath = Path.Combine(folderPath, $"img{currentIndex - 1}.jpg"); // 执行重命名 File.Move(oldFilePath, newFilePath); currentIndex++; }
代码说明
- 用
Path.Combine拼接文件路径,比手动拼接更安全,能自动适配不同系统的路径分隔符 - 循环从
deleteIndex + 1(也就是4)开始,每次检查文件是否存在,不存在就停止循环,避免出现找不到文件的错误 - 用
File.Move完成重命名操作,这是C#中重命名文件的标准方法
内容的提问来源于stack exchange,提问作者Alisha
相关产品推荐
相关产品推荐

