Move a File from one location to another
suggest changeFile.Move
One line moves a file from one path to another:
File.Move(@"C:\TemporaryFile.txt", @"C:\TemporaryFiles\TemporaryFile.txt");
A lot can still go wrong. The computer might not have a drive labeled C:, or the source file might already have been moved or might not exist.
Check that the source file exists before you move it:
string source = @"C:\TemporaryFile.txt", destination = @"C:\TemporaryFiles\TemporaryFile.txt";
if (File.Exists(source))
{
File.Move(source, destination);
}
That check only means the file existed at that moment. It can still disappear before File.Move. On .NET Framework, File.Move also cannot move a file onto a different volume. Tell the user the operation failed, or handle the exception.
A FileNotFoundException is not the only exception you are likely to encounter.
| Exception | Description |
|---|---|
IOException |
The destination file already exists, or the destination is on a different drive. |
FileNotFoundException |
The source file could not be found. |
ArgumentNullException |
source or destination is null. |
ArgumentException |
source or destination is empty, or contains invalid characters. |
UnauthorizedAccessException |
The caller does not have the required permission. |
PathTooLongException |
The source, destination, or specified paths exceed the maximum length. On Windows, a path must be less than 248 characters, and a file name must be less than 260 characters. |
DirectoryNotFoundException |
The specified directory could not be found. |
NotSupportedException |
The source or destination path or file name is in an invalid format. |
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents