
.NET 1.1+Basic File Operations (2)
When an application stores information within files, it is common to include some simple file management tasks within the software. This article describes methods of copying, moving, renaming and deleting files using C# and the .NET framework.
Moving a File
Files can be moved from one location to another, optionally changing their file name at the same time, using the Move method of the File class. This method accepts string arguments for the file to move and the new location and name. The following example moves the test file from the temp folder to a sub-folder named "subfolder" and changes its name to "Moved.txt". The target folder must exist for the operation to be successful. The method will also fail with an exception if the target file already exists.
File.Move("c:\\temp\\Test.txt", "c:\\temp\\subfolder\\Moved.txt");
The FileInfo class provides the MoveTo method to allow files to be moved. This method does not return a value. Instead, the existing FileInfo object is updated to refer to the new location and file name.
FileInfo file = new FileInfo("c:\\temp\\subfolder\\Moved.txt");
file.MoveTo("c:\\temp\\Test.txt");
Renaming a File
Neither the File class nor the FileInfo class provide a method for renaming a file. However, the Move and MoveTo methods can be used for this purpose. Instead of specifying a new folder for the moved file, the same path is used for both parameters with only the file name part being changed:
File.Move("c:\\temp\\Test.txt", "c:\\temp\\Renamed.txt");
For the FileInfo class, use the MoveTo method as follows:
FileInfo file = new FileInfo("c:\\temp\\Renamed.txt");
file.MoveTo("c:\\temp\\Test.txt");
Deleting a File
The last of the four basic operations is the deleting of files. The File class include the static Delete method to allow a file to be permanently erased. This method does not send the file to the recycle bin and gives no option for cancelling the operation, so should be used with care.
The File class' method accepts a single parameter containing the name of the file to be deleted.
File.Delete("c:\\temp\\Test.txt");
The FileInfo class also contains a Delete method. As the file name is set in the constructor, the method requires no parameters.
FileInfo file = new FileInfo("c:\\temp\\Copy.txt");
file.Delete();
22 December 2009