Move a File from one location to another

suggest change


In order to move a file from one location to another, one simple line of code can achieve this:

File.Move(@"C:\TemporaryFile.txt", @"C:\TemporaryFiles\TemporaryFile.txt");

However, there are many things that could go wrong with this simple operation. For instance, what if the user running your program does not have a Drive that is labelled ‘C’? What if they did - but they decided to rename it to ‘B’, or ‘M’?

What if the Source file (the file in which you would like to move) has been moved without your knowing - or what if it simply doesn’t exist.

This can be circumvented by first checking to see whether the source file does exist:

string source = @"C:\TemporaryFile.txt", destination = @"C:\TemporaryFiles\TemporaryFile.txt";
    File.Move(source, destination);

This will ensure that at that very moment, the file does exist, and can be moved to another location. There may be times where a simple call to File.Exists won’t be enough. If it isn’t, check again, convey to the user that the operation failed - or handle the exception.

A FileNotFoundException is not the only exception you are likely to encounter.

See below for possible exceptions:

Exception Type | Description | —— | —— |IOException | The file already exists or the source file could not be found.ArgumentNullException| The value of the Source and/or Destination parameters is null. |ArgumentException | The value of the Source and/or Destination parameters are empty, or contain invalid characters. |UnauthorizedAccessException | You do not have the required permissions in order to perform this action. |PathTooLongException | The Source, Destination or specified path(s) exceed the maximum length. On Windows, a Path’s length must be less than 248 characters, while File names must be less than 260 characters.DirectoryNotFoundException | The specified directory could not be found. |NotSupportedException | The Source or Destination paths or file names are in an invalid format.

Feedback about page:

Optional: your email if you want me to get back to you:

Table Of Contents