You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何删除文件夹内指定图片后重命名后续图片?

批量重命名后续图片的实现方案

你可以在删除指定图片后,通过循环遍历后续的图片文件,依次将它们重命名为序号减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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 06:54:23