目的
对文件夹中所有文件名实现批量修改(添加新字符)
思路
获取文件夹路径获取文件夹中所有文件的文件名对文件名进行批量修改
方法
窗口设计
获取文件夹路径 使用FolderBrowserDialog控件获取文件夹路径,并用Directory.Exists方法对路径进行检查。
FolderBrowserDialog folderBD
= new FolderBrowserDialog();
folderBD
.ShowDialog();
string folderPath
= folderBD
.SelectedPath
;
if (Directory
.Exists(folderPath
) == false)
MessageBox
.Show("文件夹不存在!\n或者输入路径不合法!", "错误");
获取文件夹中所有文件名并修改 使用DirectoryInfo、FileInfo以及File类,实现对文件夹中所有文件名的修改。
DirectoryInfo folder
= new DirectoryInfo(folderPath
);
foreach (FileInfo file
in folder
.GetFiles())
{
string oldname
= file
.FullName
;
string newname
= "New_Picture.jpg";
File
.Move(oldname
, newname
);
}
修改方式主要是在原文件名的基础上添加新字符,因此设置三种添加方式,分别是在原文件名开头、中间、末尾添加。
string oldname
= file
.FullName
;
string newname
= file
.DirectoryName
+ "\\" + addContent
+ file
.Name
;
string oldname
= file
.FullName
;
string newname
= file
.DirectoryName
+ "\\" + file
.Name
.Insert(Pos
, addContent
);
string oldname
= file
.FullName
;
string newname
= oldname
.Insert(oldname
.LastIndexOf('.'), addContent
);
最后
内容仅供大家学习参考,若有不足之处,敬请大家批评指正!