Using System.IO.File
or another .NET
class, what is the best way to rename a file?
I want to be able to rename files on local drives or on network locations.
If using System.IO.File
, is Move
the best way?
Using System.IO.File
or another .NET
class, what is the best way to rename a file?
I want to be able to rename files on local drives or on network locations.
If using System.IO.File
, is Move
the best way?
Alternatives
System.IO.File.Move
You can rename a file with
System.IO.File.Move
like this:You may be interested in keeping the same location and just change the name of the file. Sure that can be done:
System.IO.FileInfo.MoveTo
You can also use
System.IO.FileInfo.MoveTo
:Note: You can also build the destination path as shown above.
"Hand move"
Evidently you can always open the existing file, create a new one with the desired name... copy the contests from the old to the new one, and finally delete the old one. This will work given you have write access, although dates and security info (owner of the file, etc...) will not be preserved.
You can see an example of that at the accepted solution of How to write contents of one file to another file?.
Notes
Note 1: Others alternatives include:
Microsoft.VisualBasic.FileSystem.Rename
andMicrosoft.VisualBasic.FileIO.FileSystem.RenameFile
.Both
Microsoft.VisualBasic.FileSystem.Rename
andSystem.IO.File.Move
are equivalent, they do parameter checks, permissions checks and error handling aroundMoveFile
fromkernel32
.Regarding
Microsoft.VisualBasic.FileIO.FileSystem.RenameFile
, it will rename files in the same folder given the full path and the new name (similar to what I present above to build the destination path), and then fall back toMoveFile
fromkernel32
.In a similar fashion
System.IO.FileInfo.MoveTo
will callMoveFile
fromkernel32
.Note 2: It should also be noted that you cannot find
Microsoft.VisualBasic
from Mono. That means thatSystem.IO.File.Move
andSystem.IO.FileInfo.MoveTo
are the only portable options.It is all MoveFile.
As mentioned above all those methods will fallback to
MoveFile
fromkernel32
.MoveFile
will work for any mounted drive on the system (even network drives), although it should not be used to move from a volume to another. In that case it will be necessary to copy the file to the destination and remove the old file.The best alternative
Since the
Microsoft.VisualBasic.FileSystem.Rename
andMicrosoft.VisualBasic.FileIO.FileSystem.RenameFile
may not be used in other operating systems as they are not ported by Mono, I'll discard those.So, we are left with
System.IO.File.Move
andSystem.IO.FileInfo.MoveTo
. Between thoseSystem.IO.File.Move
has less overhead because it doesn't have to maintain the state of theFileInfo
object. Other than that they will work the same... so, if you are already usingFileInfo
useSystem.IO.FileInfo.MoveTo
otherwiseSystem.IO.File.Move
.And so,
System.IO.File.Move
is the best option to rename files in .NET! (They didn't give us a whacky API).Celebrate!