How to Move a File in C#

Introduction

The Move method moves an existing file to a new location with the same or a different file name.

How to move a File in C#?

The Move method takes two parameters. The Move method deletes the original file. A file Moves method a specified file to a new location, providing the option to specify a new file name.

File.Move renames a file. It is a tested .NET Framework method. The File class in the System.IO namespace provides this convenient method.

  • It performs a fast rename of the file you target.
  • It sometimes throws exceptions.

Move a File in C#

The Move method moves an existing file to a new location with the same or a different file name in File Move. The Move method takes two parameters. The Move method deletes the original file. The method that renames files is called File.Move.

We can include the System.IO namespace at the top with a using directive or specify the fully qualified name "System.IO.File.Move".

The following code snippet moves the source file to the destination file.

try
{
    File.Move(sourceFile, destinationFile);
}
catch (IOException iox)
{
    Console.WriteLine(iox.Message);
}

Example

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        string path = @"c:\temp\MySample.txt";
        string path2 = @"c:\temp2\MySample.txt";

        try
        {
            if (!File.Exists(path))
            {
                // This statement ensures that the file is created,
                // but the handle is not kept.
                using (FileStream fs = File.Create(path)) { }
            }

            // Ensure that the target does not exist.
            if (File.Exists(path2))
                File.Delete(path2);

            // Move the file.
            File.Move(path, path2);
            Console.WriteLine("{0} was moved to {1}.", path, path2);

            // See if the original exists now.
            if (File.Exists(path))
            {
                Console.WriteLine("The original file still exists, which is unexpected.");
            }
            else
            {
                Console.WriteLine("The original file no longer exists, which is expected.");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

Summary

In this article, we learned about how to move a file in C#.


Similar Articles