2017-02-20 13 views
-1

我有一个文件夹有大量的图片,都具有相同的名称格式:如何删除所有文件名的最后四个字符的文件夹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++; 
    } 
} 
+2

好了,“去掉最后三个字符”的哪一位是造成你一个问题吗?你知道'string.Substring'和'string.Length'吗? (我强烈建议在你的变量名称上加上这个'f'前缀,btw ...) –

+2

字符串替换不是一个选项吗? – apomene

+0

你有没有考虑使用Path.GetExtension?或Path.ChangeExtension? – BugFinder

回答

0
private string Remove4LastCharacter(string fName) 
{ 
    string nameWithoutExt = Path.GetFileNameWithoutExtension(fName); 
    // Length is less than or equal 4 => I can not remove them 
    if (nameWithoutExt.Length <= 4) 
    { 
     return fName; 
    } 

    // Other cases 
    string newNameWithoutExt = nameWithoutExt.Substring(0, nameWithoutExt.Length - 4); 
    return newNameWithoutExt + Path.GetExtension(fName); 
} 

应用到你的代码:

// Use Path.Combine instead 
fFromName = Path.Combine(fPath, f.Name); 
fNewName = Remove4LastCharacter(f.Name); 
fToName = string.Format("{0}_{1}{2}", Path.Combine(fPath, fNewName), i.ToString(), fExt); 
+1

这是[susbstring(startIndex,length)](https://msdn.microsoft.com/en-US/library/aka44szs(v = vs.110).aspx) - 所以,我会说它必须是'nameWithoutExt .Substring(0,nameWithoutExt.Length - 4);' – Fildor

+0

@Fildor哦,谢谢,我在那里看到我的错误。 – GSP

相关问题