目的
- 对文件夹中所有文件名实现批量修改(添加新字符)
思路
- 获取文件夹路径
- 获取文件夹中所有文件的文件名
- 对文件名进行批量修改
方法
- 窗口设计
- 获取文件夹路径
使用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);
}
修改方式主要是在原文件名的基础上添加新字符,因此设置三种添加方式,分别是在原文件名开头、中间、末尾添加。
//addContent为要添加的内容//在开头添加
string oldname = file.FullName;
string newname = file.DirectoryName + "\\" + addContent + file.Name;//在中间添加
//Pos为要添加在原文件名的哪个位置
string oldname = file.FullName;
string newname = file.DirectoryName + "\\" + file.Name.Insert(Pos, addContent);//在末尾添加
string oldname = file.FullName;
string newname = oldname.Insert(oldname.LastIndexOf('.'), addContent);
最后
- 源代码在如下链接中:https://download.csdn.net/download/qq_39373443/11384221
- 内容仅供大家学习参考,若有不足之处,敬请大家批评指正!