我以前写了一个这样的工具,就是批量将文件夹,以及子文件夹下的文件名按照表达式批量更改名称.

介绍了一个使用C#编写的批量文件重命名工具的核心代码实现,该工具能够递归地遍历指定目录及其子目录下的所有文件,并根据正则表达式进行文件名的批量替换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
我以前写了一个这样的工具,就是批量将文件夹,以及子文件夹下的文件名按照表达式批量更改名称.
用2003写的,以下是核心代码:
private void Rename(string folderPath)
 {
  string fileName = "unnamed";
  string fileExtension = "";
  System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(folderPath);
  foreach(System.IO.FileSystemInfo fsi in di.GetFileSystemInfos())
  {
   if(fsi is System.IO.DirectoryInfo)
   {
    Rename(fsi.FullName);
   }
   else
   {
    fileName = fsi.Name;
    int lastDot = fileName.LastIndexOf('.');
    if(lastDot != -1) //这样操作,可以处理没有扩展名的文件
    {
     fileExtension = fileName.Substring(lastDot); //取得文件扩展名
     fileName = fileName.Substring(0,lastDot);    //get file name without extension.
    }
     
    fileName = System.Text.RegularExpressions.Regex.Replace(fileName,this.txtRegex.Text.Trim(),this.txtReplace.Text.Trim());
    fileName += fileExtension;
    try
    {
     if(fileName == fsi.Name) continue; //文件名没有改变.
      System.IO.File.Move(fsi.FullName,folderPath + "\\" + fileName);
      this.listBox.Items.Add(fsi.Name + "\t\t moved to \t\t" + fileName);
    }
    catch
    {
     //throw;
      this.listBox.Items.Add(fsi.Name + "\t\t can't move to \t\t" + fileName);
    }
   }
  }// end foreach
 }//end method

表达式(txtRegex.Text):\[\d+\]] ;txtReplace.Text 为"";结果如下
1516178994_483324109c_s[1].jpg   moved to   1516178994_483324109c_s.jpg
1554855298_e1a68da37c_s[1].jpg   moved to   1554855298_e1a68da37c_s.jpg
aiga-25[1].gif   moved to   aiga-25.gif
bg-top[1].gif   moved to   bg-top.gif 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值