0
0
CsharpHow-ToBeginner · 3 min read

How to Move a File in C#: Simple Guide with Examples

In C#, you can move a file using the File.Move method from the System.IO namespace. This method takes the source file path and the destination file path as arguments and moves the file to the new location.
📐

Syntax

The File.Move method moves a file from one location to another.

  • sourceFileName: The path of the file to move.
  • destFileName: The new path where the file will be moved.

If the destination file exists, an exception will be thrown.

csharp
File.Move(string sourceFileName, string destFileName);
💻

Example

This example shows how to move a file named example.txt from one folder to another. It also handles exceptions if the file does not exist or the destination file already exists.

csharp
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string sourcePath = "C:\\Temp\\example.txt";
        string destinationPath = "C:\\Temp\\Archive\\example.txt";

        try
        {
            File.Move(sourcePath, destinationPath);
            Console.WriteLine("File moved successfully.");
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Source file not found.");
        }
        catch (IOException ex)
        {
            Console.WriteLine($"Error moving file: {ex.Message}");
        }
    }
}
Output
File moved successfully.
⚠️

Common Pitfalls

  • Trying to move a file when the source file does not exist causes a FileNotFoundException.
  • If the destination file already exists, File.Move throws an IOException.
  • Make sure the program has permission to access both source and destination paths.
  • Use Directory.CreateDirectory to ensure the destination folder exists before moving.
csharp
/* Wrong way: destination file exists, causes exception */
// File.Move("C:\Temp\example.txt", "C:\Temp\Archive\example.txt");

/* Right way: check if destination exists and delete or rename before moving */
if (File.Exists("C:\Temp\Archive\example.txt"))
{
    File.Delete("C:\Temp\Archive\example.txt");
}
File.Move("C:\Temp\example.txt", "C:\Temp\Archive\example.txt");
📊

Quick Reference

Remember these tips when moving files in C#:

  • Use File.Move(source, destination) to move files.
  • Check if the source file exists before moving.
  • Ensure the destination directory exists.
  • Handle exceptions for missing files or existing destination files.

Key Takeaways

Use System.IO.File.Move to move files by specifying source and destination paths.
Ensure the source file exists and the destination file does not exist to avoid exceptions.
Handle exceptions like FileNotFoundException and IOException to make your code robust.
Create the destination directory if it does not exist before moving the file.
Always check permissions for accessing source and destination paths.