81

I couldn't find a DirectoryInfo.Rename(To) or FileInfo.Rename(To) method anywhere. So, I wrote my own and I'm posting it here for anybody to use if they need it, because let's face it : the MoveTo methods are overkill and will always require extra logic if you just want to rename a directory or file :

public static class DirectoryExtensions
{
    public static void RenameTo(this DirectoryInfo di, string name)
    {
        if (di == null)
        {
            throw new ArgumentNullException("di", "Directory info to rename cannot be null");
        }

        if (string.IsNullOrWhiteSpace(name))
        {
            throw new ArgumentException("New name cannot be null or blank", "name");
        }

        di.MoveTo(Path.Combine(di.Parent.FullName, name));

        return; //done
    }
}
B.K.
  • 9,982
  • 10
  • 73
  • 105
Alex Marshall
  • 10,162
  • 15
  • 72
  • 117

3 Answers3

147

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • 18
    Pay attention that switching cases like `foo` to `Foo` will throw an IOException when done with a simple `Directory.Move` as both are regarded as the same path. So there is a difference... just saying. – Kabbalah Oct 29 '15 at 15:05
75

You should move it:

Directory.Move(source, destination);
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
19

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

jsmith
  • 7,198
  • 6
  • 42
  • 59
  • 10
    All they do is validate parameters and call `Directory.Move` and `File.Move`. I checked. – SLaks Jan 07 '10 at 22:12
  • 4
    Yes, agreed. I think his complaint is because "Move" does not make you automatically think "Rename." If he wants the Syntax, it exists in that format, just in another namespace. – jsmith Jan 07 '10 at 22:15
  • 1
    Move means rename for any unix user :) – aloisdg Aug 20 '18 at 18:09