2016-08-22 97 views
0

我需要重命名多個CSV文件名。我想刪除「 - 」後面的所有內容,例如「File-1.csv」將變成「File.csv」。這裏是我的代碼,不工作:使用子串重命名多個文件名使用C#

DirectoryInfo d = new DirectoryInfo(@"C:\folder"); 
FileInfo[] infos = d.GetFiles(); 
foreach (FileInfo f in infos) 
{ 
    File.Move(f.FullName, f.FullName.ToString().Substring(0, f.LastIndexOf('-'))); 
} 

我得到這個錯誤:

Error 2 'System.IO.FileInfo' does not contain a definition for 'LastIndexOf' and no extension method 'LastIndexOf' accepting a first argument of type 'System.IO.FileInfo' could be found (are you missing a using directive or an assembly reference?)

我該如何解決這個問題?

+2

那麼它在做什麼與你想要它做什麼? (我的猜測是它將刪除擴展名 - 所以這就是你應該看到的。這與「多個」部分無關......讓它爲單個文件工作,我希望它可以與) –

+0

嗨,我得到這個錯誤 - 錯誤'System.IO.FileInfo'沒有包含'LastIndexOf'的定義,也沒有擴展方法'LastIndexOf'接受'System.IO'類型的第一個參數。 FileInfo'可以找到(你錯過了一個使用指令或程序集引用嗎?) – user3206687

+0

我真的很新的C#和我認爲這意味着命名空間失蹤,但我累了使用谷歌搜索,我不能解決它 – user3206687

回答

1

由於您在FileInfo對象上調用.LastIndexOf()時,您當前的代碼無法編譯,因此您應該在FileInfo.FullName上調用它。您的子字符串也會從文件名字符串中刪除擴展名,我認爲您不需要。下面是保留的擴展的解決方案:

foreach (FileInfo f in infos) 
{ 
    // Get the extension string from the existing file 
    var extension = f.FullName.Substring(f.FullName.LastIndexOf('.'), f.FullName.Length - 1); 

    // Get the filename, excluding the '-' as well as the extension 
    var filename = f.FullName.SubString(0, f.FullName.LastIndexOf('-')); 

    // Concatenate the filename and extension and move the file 
    File.Move(f.FullName, String.Format("{0}{1}", filename, extension)); 
}  
+0

我認爲這個解決方案仍然會錯過文件擴展名的權利? –

+0

@ Sam.C更新了更詳細的解決方案,保留了擴展名。 –

+0

非常感謝你的幫助:) – user3206687

0

I'm getting this error:

Error 2 'System.IO.FileInfo' does not contain a definition for 'LastIndexOf'

f不是串;嘗試f.FullName.LastIndexOf ...