我有一个文件夹有大量的图片,都具有相同的名称格式:如何删除所有文件名的最后四个字符的文件夹C#
some-random-name-min.jpg
another-random-name-min.jpg
and-another-random-name-min.jpg
我想要去除最后-min 在这里我做了一个脚本来更改所有文件的名称,但我只想删除最后四个字符。
private void Rename(string fPath, string fNewName)
{
string fExt;
string fFromName;
string fToName;
int i = 1;
//copy all files from fPath to files array
FileInfo[] files = new DirectoryInfo(fPath).GetFiles();
//loop through all files
foreach (var f in files)
{
//get the filename without the extension
fFromName = Path.GetFileNameWithoutExtension(f.Name);
//get the file extension
fExt = Path.GetExtension(f.Name);
//set fFromName to the path + name of the existing file
fFromName = string.Format(@"{0}\{1}", fPath, f.Name);
//set the fToName as path + new name + _i + file extension
fToName = string.Format(@"{0}\{1}_{2}{3}", fPath, fNewName, i.ToString(), fExt);
//rename the file by moving to the same place and renaming
File.Move(fFromName, fToName);
//increment i
i++;
}
}
好了,“去掉最后三个字符”的哪一位是造成你一个问题吗?你知道'string.Substring'和'string.Length'吗? (我强烈建议在你的变量名称上加上这个'f'前缀,btw ...) –
字符串替换不是一个选项吗? – apomene
你有没有考虑使用Path.GetExtension?或Path.ChangeExtension? – BugFinder