在C#中修改文件名
发布网友
发布时间:2022-10-03 17:55
我来回答
共2个回答
热心网友
时间:2023-10-11 06:51
我以前写了一个这样的工具,就是批量将文件夹,以及子文件夹下的文件名按照表达式批量更改名称.
用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
热心网友
时间:2023-10-11 06:51
用System.IO.File.Move(源文件名,新文件名)