Rename a file in C#

后端 未结 18 854
北荒
北荒 2020-11-22 15:05

How do I rename a file using C#?

18条回答
  •  忘了有多久
    2020-11-22 15:25

    1. First solution

      Avoid System.IO.File.Move solutions posted here (marked answer included). It fails over networks. However, copy/delete pattern works locally and over networks. Follow one of the move solutions, but replace it with Copy instead. Then use File.Delete to delete the original file.

      You can create a Rename method to simplify it.

    2. Ease of use

      Use the VB assembly in C#. Add reference to Microsoft.VisualBasic

      Then to rename the file:

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

      Both are strings. Note that myfile has the full path. newName does not. For example:

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

      The C:\whatever\ folder will now contain b.txt.

提交回复
热议问题