2012-09-18 36 views
1

環境:Visual Studio 2010,Windows窗體應用程序。在C#中重命名文件組(Windows Forms應用程序)

嗨!我想重命名(批處理)一些文件... 1.我有(約50000個文件):abc.mp3 .MP3

2. 我有(約50 000文件):abc.mp3,def.mp3,ghi.mp3 我想:1abc.mp3,1def.mp3,1ghi.mp3

類似的東西...

FolderBrowserDialog folderDlg = new FolderBrowserDialog(); 
    folderDlg.ShowDialog(); 

    string[] mp3Files = Directory.GetFiles(folderDlg.SelectedPath, "*.mp3"); 
    string[] newFileName = new string[mp3Files.Length]; 

    for (int i = 0; i < mp3Files.Length; i++) 
    { 
     string filePath = System.IO.Path.GetDirectoryName(mp3Files[i]); 
     string fileExt = System.IO.Path.GetExtension(mp3Files[i]); 

     newFileName = mp3Files[i]; 

     File.Move(mp3Files[i], filePath + "\\" + newFileName[1] + 1 + fileExt); 
    } 

但是這段代碼不起作用。錯誤在這裏... newFileName = mp3Files[i]; 我無法正確轉換它。 謝謝!

+1

'newFileName'是串的陣列,而'mp3Files [I]'是一個字符串。您不能將單個字符串分配給一個字符串數組。 –

+0

@MetroSmurf,我認爲這是代碼的問題,你的評論應該是一個答案 – Habib

+0

是的!我知道。那我該如何解決呢?我總是遇到轉換問題。 – user922907

回答

4

最快的選擇將使用直接的操作系統重命名功能。使用過程對象以/ C開關運行shell CMD。使用「ren」命令行重命名。

Process cmd = new Process() 
{ 
    StartInfo = new ProcessStartInfo() 
    { 
     FileName = "cmd.exe", 
     Arguments = @"/C REN c:\full\path\*.mp3 c:\full\path\1*.mp3" 
    } 
}; 

cmd.Start(); 
cmd.WaitForExit(); 

//Second example below is for renaming with file.mp3 to file1.mp3 format 
cmd.StartInfo.Arguments = @"/C REN c:\full\path\*.mp3 c:\full\path\*1.mp3"; 
cmd.Start(); 
cmd.WaitForExit(); 
+0

我喜歡你的代碼:)謝謝loopedcode –

+0

如果你喜歡投票:) :) – loopedcode

+0

+1,更好的方法 – Habib

0

在評論中討論的朋友,你可以聲明newFileName作爲一個簡單的字符串(字符串數組來代替),或者如果您打算使用數組使用下面的代碼:

newFileName[i] = mp3Files[i]; 

和自你正在使用循環,你最好使用字符串,而不是字符串數組。

2

嘗試此代碼,而不是:

Directory.GetFiles(folderDlg.SelectedPath, "*.mp3") 
    .Select(fn => new 
    { 
     OldFileName = fn, 
     NewFileName = String.Format("{0}1.mp3", fn.Substring(fn.Length - 4)) 
    }) 
    .ToList() 
    .ForEach(x => File.Move(x.OldFileName, x.NewFileName)); 
+0

我認爲loopedcode的代碼具有更好的性能,但您的代碼也值得+1,寫得很好 –

相關問題