CodeGym /Courses /C# SELF /Moving files and directories

Moving files and directories

C# SELF
Level 40 , Lesson 3
Available

1. Introduction

There are tons of scenarios where move operations are needed: moving "downloaded" files from a temp folder to a Documents folder, bulk organizing photos, renaming by a pattern, processing mail and logs. The filesystem likes order — or at least something resembling it! And a good developer should know how to impose that order.

Also these tasks often pop up in interviews: "Write a utility that renames all files by adding a version number" or "Create a command that moves obsolete documents to an archive". Let's see how to do this in C#.

Overview of options

In .NET there are two main ways to move and rename — use the static methods (File.Move, Directory.Move) or the instance methods (FileInfo.MoveTo, DirectoryInfo.MoveTo). Under the hood these methods do almost the same thing — mostly the syntax differs.

How does .NET "see" moving and renaming?

Attention! Renaming and moving are essentially the same operation: a file or folder is identified by its path in the filesystem. If the path changes — it's considered that the object was "moved" or "renamed". If you change only the name but keep the same directory — that's a rename. If you change the whole path — that's a move. Philosophy like Schrödinger: the object is both moved and renamed if you provide a new path with a new name!

2. Moving and renaming files: examples

We'll go from simple to complex and continue based on our mini file manager.

Static method File.Move

Here's an example of how to move (or rename) a file:


// Move the file test1.txt to another folder with a new name
File.Move(@"C:\Temp\test1.txt", @"C:\Archive\test1_archived.txt");

And if you just want to rename a file in the same folder:


// Just change the file name
File.Move(@"C:\Temp\test1.txt", @"C:\Temp\test_renamed.txt");

That's the whole magic! .NET simply "cuts" one path and "assigns" another to the object, if both paths are accessible and there are no conflicts.

Static method Directory.Move

With folders it's similar:


// Move a directory
Directory.Move(@"C:\Temp\OldFolder", @"C:\Temp\NewFolder");

You can rename a folder (new name in the same directory) or move it entirely to another location.

3. Instance methods: FileInfo.MoveTo and DirectoryInfo.MoveTo

When you already have a FileInfo or DirectoryInfo object, you can call MoveTo():


var fileInfo = new FileInfo(@"C:\Temp\test1.txt");
fileInfo.MoveTo(@"C:\Archive\test1_archived.txt");

// Folders:
var dirInfo = new DirectoryInfo(@"C:\Temp\OldFolder");
dirInfo.MoveTo(@"C:\Temp\NewFolder");

Again: if the new path is the same folder but with a different name, it's a rename; if it's a different folder — it's a move.

4. What if the file already exists at the destination?

Here the nuances start that like to "bite" at the worst moment.

File.Move

If a file already exists at the destination path — an IOException will be thrown, and your code will "crash":


try
{
    File.Move("data.txt", "archive\\data.txt");
}
catch (IOException ex)
{
    Console.WriteLine("Destination file already exists! " + ex.Message);
}

FileInfo.MoveTo

Exactly the same picture — IOException if the destination file already exists.

Directory.Move

With folders it's even stricter: if the target folder already exists — an exception. You can't move a folder into a folder that's already occupied.

Takeaway: Always check whether a file or folder already exists where you're trying to write!


// Calmly check if the file exists at the target path
if (!File.Exists("archive\\data.txt"))
{
    File.Move("data.txt", "archive\\data.txt");
}
else
{
    Console.WriteLine("Destination file already exists!");
}

5. Useful nuances

Example: renaming a folder


var oldDir = @"C:\Projects\OldReport";
var newDir = @"C:\Projects\NewReport";

// Check that the new directory does not exist and the old one does
if (Directory.Exists(oldDir) && !Directory.Exists(newDir))
{
    Directory.Move(oldDir, newDir);
    Console.WriteLine("Folder successfully renamed.");
}
else
{
    Console.WriteLine("Error: source folder not found or new one already exists.");
}

Renaming with nested content in mind

All contents of the folder (subfolders, files) move with it without any extra commands! Convenient: one command moves a folder with any nesting to the new location.

Best practices and useful methods from Path

When renaming or moving files, use methods from System.IO.Path to build the new path correctly or change the file name:

  • Get file name without extension: Path.GetFileNameWithoutExtension(path)
  • Change only the extension: Path.ChangeExtension(path, ".bak")
  • Build a new path with a different name: Path.Combine(Path.GetDirectoryName(path), "newname.txt")

string oldPath = @"C:\Reports\2023_Final.docx";
string newName = "2023_Archive.docx";
string newPath = Path.Combine(Path.GetDirectoryName(oldPath)!, newName);

File.Move(oldPath, newPath);

6. Important nuances and common mistakes

Access rights and locking

If you don't have write permission on one of the paths — an UnauthorizedAccessException will be thrown. Likewise, if the file is used by another process (for example, opened in Word), you'll get an error. This is very common.

Moving between different drives and volumes

Essentially, File.Move implements a fast rename operation within the same volume/drive. If you try to move a file from drive C to drive D — .NET will automatically perform a copy followed by deletion of the source file. If something goes wrong (for example, destination drive is full), the source file will remain in place.

Interesting fact: almost all modern filesystems support "fast rename/move" within a volume, and when moving between volumes — copy + delete.

Moving whole folders (Directory.Move)

You can't move a folder into itself or into a subfolder of itself (for example, C:\Data into C:\Data\Archive) — that will cause an error.

How to move safely?

Before any move, especially bulk moves, check the existence of the source (File.Exists, Directory.Exists) and the absence of conflicts at the destination. And don't forget about try-catch: the filesystem is capricious and can throw an error at the most unexpected moment.

2
Task
C# SELF, level 40, lesson 3
Locked
Moving all files from one folder to another
Moving all files from one folder to another
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION