在C#中修改文件名

用c#的方法将原文件批量修改或新文件名, 比如说 20090702020024058[1].jpg 将改为 20090702020024058.jpg

我以前写了一个这样的工具,就是批量将文件夹,以及子文件夹下的文件名按照表达式批量更改名称.
用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
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2018-03-07
用System.IO.File.Move(源文件名,新文件名)本回答被提问者和网友采纳
相似回答