Renaming a directory in C#

C#File IoDirectoryRename

C# Problem Overview


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
	}
}

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

You should move it:

Directory.Move(source, destination);

Solution 3 - C#

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlex MarshallView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Rubens FariasView Answer on Stackoverflow
Solution 3 - C#jsmithView Answer on Stackoverflow