2010-07-10 94 views
451

如何使用C#重命名文件?以C#重命名文件

+0

我討厭補充一點,有一個問題在這裏所有的解決方案在這裏,特別是如果你做比較,並正在從一個位置的文件到另一個(目錄以及文件名),因爲你應該知道一個卷可能是一個交匯點......所以如果newname是q:\ SomeJunctionDirectory \ hello.txt並且舊名稱是c:\ TargetOfJunctionPoint \ hello。 TXT ...文件是相同的,但名稱不是。 – 2016-10-14 01:26:18

回答

688

看看System.IO.File.Move,將文件「移動」到一個新名稱。

System.IO.File.Move("oldfilename", "newfilename"); 
+9

當文件名僅在字母大小寫方面不同時,此解決方案不起作用。例如file.txt和File.txt – SepehrM 2014-07-06 20:31:19

+2

@SepehrM,我只是再次檢查,它在我的Windows 8.1機器上正常工作。 – 2014-07-07 01:57:19

+0

我不知道爲什麼發生這種情況,但看看這些帖子:http://stackoverflow.com/questions/8152731/file-or-folder-rename-to-lower-case-in-c-sharp-using -directoryinfo-fileinfo-move和http://www.codeproject.com/Tips/365773/Rename-a-directory-or-file-name-to-lower-case-with – SepehrM 2014-07-07 06:43:55

100
System.IO.File.Move(oldNameFullPath, newNameFullPath); 
-11

另外,在C#所沒有的一些功能,我用C++或C:

public partial class Program 
{ 
    [DllImport("msvcrt", CallingConvention = CallingConvention.Cdecl, SetLastError = true)] 
    public static extern int rename(
      [MarshalAs(UnmanagedType.LPStr)] 
      string oldpath, 
      [MarshalAs(UnmanagedType.LPStr)] 
      string newpath); 

    static void FileRename() 
    { 
     while (true) 
     { 
      Console.Clear(); 
      Console.Write("Enter a folder name: "); 
      string dir = Console.ReadLine().Trim('\\') + "\\"; 
      if (string.IsNullOrWhiteSpace(dir)) 
       break; 
      if (!Directory.Exists(dir)) 
      { 
       Console.WriteLine("{0} does not exist", dir); 
       continue; 
      } 
      string[] files = Directory.GetFiles(dir, "*.mp3"); 

      for (int i = 0; i < files.Length; i++) 
      { 
       string oldName = Path.GetFileName(files[i]); 
       int pos = oldName.IndexOfAny(new char[] { '0', '1', '2' }); 
       if (pos == 0) 
        continue; 

       string newName = oldName.Substring(pos); 
       int res = rename(files[i], dir + newName); 
      } 
     } 
     Console.WriteLine("\n\t\tPress any key to go to main menu\n"); 
     Console.ReadKey(true); 
    } 
} 
+18

C#完全有能力重命名文件。 – 2012-10-26 04:53:26

+67

我無言以對 – 2013-05-10 19:17:48

4

注:在這個例子的代碼,我們打開一個目錄,搜索與打開的PDF文件,並在關閉括號文件的名稱。您可以檢查並替換您喜歡的名稱中的任何字符,或者使用替換功能指定一個全新的名稱。

還有其他的方法可以從這段代碼中做更多詳細的重命名,但我的主要目的是展示如何使用File.Move來執行批量重命名。當我在筆記本上運行它時,這對180個目錄中的335個PDF文件起作用。這是時代代碼的激勵,並且有更多精細的方法來實現它。

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace BatchRenamer 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var dirnames = Directory.GetDirectories(@"C:\the full directory path of files to rename goes here"); 

      int i = 0; 

      try 
      { 
       foreach (var dir in dirnames) 
       { 
        var fnames = Directory.GetFiles(dir, "*.pdf").Select(Path.GetFileName); 

        DirectoryInfo d = new DirectoryInfo(dir); 
        FileInfo[] finfo = d.GetFiles("*.pdf"); 

        foreach (var f in fnames) 
        { 
         i++; 
         Console.WriteLine("The number of the file being renamed is: {0}", i); 

         if (!File.Exists(Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", "")))) 
         { 
          File.Move(Path.Combine(dir, f), Path.Combine(dir, f.ToString().Replace("(", "").Replace(")", ""))); 
         } 
         else 
         { 
          Console.WriteLine("The file you are attempting to rename already exists! The file path is {0}.", dir); 
          foreach (FileInfo fi in finfo) 
          { 
           Console.WriteLine("The file modify date is: {0} ", File.GetLastWriteTime(dir)); 
          } 
         } 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       Console.WriteLine(ex.Message); 
      } 
      Console.Read(); 
     } 
    } 
} 
+3

這完全不是問題所在,關於3年前剛剛回答的問題。 – Nyerguds 2013-11-19 11:33:36

+1

這是一個有效的例子。誇大其辭,可能並不重要。 +1 – Adam 2013-11-27 09:11:15

+1

@Adam:這是一個非常具體的實現,就是三年前已經給出的答案,這個問題不是關於任何具體實現的問題。看不出這是如何具有建設性的。 – Nyerguds 2013-12-05 10:52:38

34

在File.Move方法中,如果文件已存在,則不覆蓋文件。它會拋出一個異常。

所以我們需要檢查文件是否存在。

/* Delete the file if exists, else no exception thrown. */ 

File.Delete(newFileName); // Delete the existing file if exists 
File.Move(oldFileName,newFileName); // Rename the oldFileName into newFileName 

或者用try catch包圍它以避免異常。

+11

對這種方法非常小心......如果你的目標目錄和你的源目錄是相同的,而「newname」實際上是「oldFileName」的區分大小寫的版本,你將在你有機會移動你的文件之前刪除它。 – 2016-10-14 01:16:41

+0

您也不能僅僅檢查字符串是否相等,因爲有多種方式來表示單個文件路徑。 – 2017-12-13 22:03:11

23

只需添加:

namespace System.IO 
{ 
    public static class ExtendedMethod 
    { 
     public static void Rename(this FileInfo fileInfo, string newName) 
     { 
      fileInfo.MoveTo(fileInfo.Directory.FullName + "\\" + newName); 
     } 
    } 
} 

然後......

FileInfo file = new FileInfo("c:\test.txt"); 
file.Rename("test2.txt"); 
+1

如果一個子文件夾已存在,稱爲newName – 2014-12-15 20:34:19

+0

...「\\」+ newName + fileInfo.Extension – mac10688 2016-02-15 18:22:35

+10

eww ...這將不起作用...使用Path.Combine()而不是彙編文件。 – 2016-10-14 01:19:09

4

用途:

Using System.IO; 

string oldFilePath = @"C:\OldFile.txt"; // Full path of old file 
string newFilePath = @"C:\NewFile.txt"; // Full path of new file 

if (File.Exists(newFilePath)) 
{ 
    File.Delete(newFilePath); 
} 
File.Move(oldFilePath, newFilePath); 
+2

如果你打算這樣做,我會建議在做任何事之前檢查'oldFilePath'是否存在......否則你會無緣無故地刪除'newFilePath'。 – 2014-07-09 19:18:45

+0

這是否甚至編譯('使用System.IO;')? – 2016-06-12 14:51:56

18
  1. 首先解決

    Avoi d System.IO.File.Move在這裏發佈的解決方案(標記爲答案)。 它通過網絡故障。但是,複製/刪除模式可以在本地和網絡上使用。按照其中一個移動解決方案進行操作,但將其替換爲Copy。然後使用File.Delete刪除原始文件。

    您可以創建一個Rename方法來簡化它。

  2. 易於使用

    的使用VB組件在C#。 添加引用Microsoft.VisualBasic程序

    然後重命名的文件:

    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(myfile, newName);

    兩者都是字符串。請注意,myfile具有完整路徑。 newName不。 例如:

    a = "C:\whatever\a.txt"; 
    b = "b.txt"; 
    Microsoft.VisualBasic.FileIO.FileSystem.RenameFile(a, b); 
    

    C:\whatever\文件夾現在將包含b.txt

+7

只是讓你知道,Microsoft.VisualBasic.FileIO.FileSystem.RenameFile調用File.Move。其他感謝正常化原始文件,並對參數進行一些額外的錯誤檢查。文件存在,文件名不爲空等,然後調用File.Move。 – 2014-07-07 02:07:03

+0

除非Copy()複製所有文件流,我認爲它沒有,我會遠離使用刪除/複製。我假設Move(),至少在停留在同一個文件系統上時,只是重命名,因此所有文件流都將保留。 – nickdu 2016-12-01 00:54:25

10

你可以將它複製爲一個新的文件,然後刪除使用System.IO.File類舊:

if (File.Exists(oldName)) 
{ 
    File.Copy(oldName, newName, true); 
    File.Delete(oldName); 
} 
+4

注意:讀取此內容的任何人:這是一種反模式,該文件可能會被另一個進程或操作系統刪除或重命名,檢查它是否存在以及是否調用複製。你需要改用try catch。 – user9993 2016-04-20 15:31:36

+0

如果卷是相同的,這也是I/O的巨大浪費,因爲移動實際上會在目錄信息級別進行重命名。 – 2016-10-14 01:20:57

1

移動在做同樣=複製和刪除舊的。

File.Move(@"C:\ScanPDF\Test.pdf", @"C:\BackupPDF\" + string.Format("backup-{0:yyyy-MM-dd_HH:mm:ss}.pdf",DateTime.Now)); 
+1

誠然,如果你關心的只是最終結果。在內部,並非如此。 – Michael 2015-12-18 23:08:12

+0

不,移動肯定不會複製和刪除。 – 2017-03-07 09:29:17

1

希望!這對你有幫助。 :)

public static class FileInfoExtensions 
    { 
     /// <summary> 
     /// behavior when new filename is exist. 
     /// </summary> 
     public enum FileExistBehavior 
     { 
      /// <summary> 
      /// None: throw IOException "The destination file already exists." 
      /// </summary> 
      None = 0, 
      /// <summary> 
      /// Replace: replace the file in the destination. 
      /// </summary> 
      Replace = 1, 
      /// <summary> 
      /// Skip: skip this file. 
      /// </summary> 
      Skip = 2, 
      /// <summary> 
      /// Rename: rename the file. (like a window behavior) 
      /// </summary> 
      Rename = 3 
     } 
     /// <summary> 
     /// Rename the file. 
     /// </summary> 
     /// <param name="fileInfo">the target file.</param> 
     /// <param name="newFileName">new filename with extension.</param> 
     /// <param name="fileExistBehavior">behavior when new filename is exist.</param> 
     public static void Rename(this System.IO.FileInfo fileInfo, string newFileName, FileExistBehavior fileExistBehavior = FileExistBehavior.None) 
     { 
      string newFileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(newFileName); 
      string newFileNameExtension = System.IO.Path.GetExtension(newFileName); 
      string newFilePath = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileName); 

      if (System.IO.File.Exists(newFilePath)) 
      { 
       switch (fileExistBehavior) 
       { 
        case FileExistBehavior.None: 
         throw new System.IO.IOException("The destination file already exists."); 
        case FileExistBehavior.Replace: 
         System.IO.File.Delete(newFilePath); 
         break; 
        case FileExistBehavior.Rename: 
         int dupplicate_count = 0; 
         string newFileNameWithDupplicateIndex; 
         string newFilePathWithDupplicateIndex; 
         do 
         { 
          dupplicate_count++; 
          newFileNameWithDupplicateIndex = newFileNameWithoutExtension + " (" + dupplicate_count + ")" + newFileNameExtension; 
          newFilePathWithDupplicateIndex = System.IO.Path.Combine(fileInfo.Directory.FullName, newFileNameWithDupplicateIndex); 
         } while (System.IO.File.Exists(newFilePathWithDupplicateIndex)); 
         newFilePath = newFilePathWithDupplicateIndex; 
         break; 
        case FileExistBehavior.Skip: 
         return; 
       } 
      } 
      System.IO.File.Move(fileInfo.FullName, newFilePath); 
     } 
    } 

如何使用此代碼?

class Program 
    { 
     static void Main(string[] args) 
     { 
      string targetFile = System.IO.Path.Combine(@"D://test", "New Text Document.txt"); 
      string newFileName = "Foo.txt"; 

      // full pattern 
      System.IO.FileInfo fileInfo = new System.IO.FileInfo(targetFile); 
      fileInfo.Rename(newFileName); 

      // or short form 
      new System.IO.FileInfo(targetFile).Rename(newFileName); 
     } 
    } 
0

在我的情況,我想重命名的文件名是唯一的,所以我添加了一個日期時間戳的名字。這樣一來,「舊」的日誌的文件名始終是唯一的:

if (File.Exists(clogfile)) 
      { 
       Int64 fileSizeInBytes = new FileInfo(clogfile).Length; 
       if (fileSizeInBytes > 5000000) 
       { 
        string path = Path.GetFullPath(clogfile); 
        string filename = Path.GetFileNameWithoutExtension(clogfile); 
        System.IO.File.Move(clogfile, Path.Combine(path, string.Format("{0}{1}.log", filename, DateTime.Now.ToString("yyyyMMdd_HHmmss")))); 
       } 
      }