Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Renaming a directory in C# [closed]

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     } } 
like image 891
Alex Marshall Avatar asked Jan 07 '10 21:01

Alex Marshall


People also ask

How do you rename a directory?

You rename a directory by moving it to a different name. Use the mv command to rename directories. You can also use mv to move a directory to a location within another directory. In this example, the directory carrots is moved from veggies to veggies2 with the mv command.

How do you rename something in C?

To rename a file in C, use rename() function of stdio. h. rename() function takes the existing file name and new file names as arguments and renames the file. rename() returns 0 if the file is renamed successfully, else it returns a non-zero value.

How do I rename a directory in DOS?

Renaming a directory in MS-DOS is much like renaming a file. Use the ren or rename command to rename the directory. Because you cannot have a file and directory of the same name, you don't need to worry about mistakenly renaming a file instead of a directory. The only exception is if you're using wild characters.

What is rename function in C?

Description. The C library function int rename(const char *old_filename, const char *new_filename) causes the filename referred to by old_filename to be changed to new_filename.


2 Answers

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.

like image 163
SLaks Avatar answered Oct 30 '22 03:10

SLaks


You should move it:

Directory.Move(source, destination); 
like image 33
Rubens Farias Avatar answered Oct 30 '22 02:10

Rubens Farias