C# 批量修改文件名称

it2022-05-05  138

目的

对文件夹中所有文件名实现批量修改(添加新字符)

思路

获取文件夹路径获取文件夹中所有文件的文件名对文件名进行批量修改

方法

窗口设计

获取文件夹路径 使用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);

最后

内容仅供大家学习参考,若有不足之处,敬请大家批评指正!

最新回复(0)