C# System.IO.File Class
The System.IO.File class is a static class that exposes methods to manipulate an existing file in a directory. Such methods allow you to create, delete, open, move or copy a file. As you can see, we need to import the System.IO namespace to be able to use the File class. The following are the some of the useful methods of the File class.
|Copy||Copies a file to a specified destination.|
|Create||Creates a file in the specified path.|
|Delete||Deletes the file.|
|Open||Returns a FileStream object that you can use to read and write to the file.|
|Move||Moves a file to a specified destination.|
|Exists||Checks whether the specified file path exists in the file system.|
Creating a File
We can use the Create method to create a new file. The method accepts a string argument which is the path where you want the file to be stored.
Note that if the file already exists, then it will be overwritten. You can use the Exists() method to test whether a certain path already exist It returns true if it finds the file path or directory path in the file system. If not, then false will be returned.
if (File.Exists(@"C:Filessample.txt")) Console.WriteLine("Path already exist."); else Console.WriteLine("Path does not exist.");
Deleting a File
To delete a file, simply use the Delete method and indicate the path of the file to be deleted.
Copying a File
We can use the Copy method that has two parameters. The first one is the source file path, and the second parameter is the destination file path.
Another overload of the Copy method provides a third boolean parameter that indicates whether to overwrite the file with the same filename in the destination path.
File.Copy(@"C:Sourcesample.txt", @"C:Destsample.txt", true);
Moving a File
If you want to move a file to another destination, you can use the Move method which also accepts two arguments which are the source and destination path.
Opening a File
You can use the Open method to open a file. The term open here doesn’t mean execute the file. Calling the Open method returns a FileStream object which you can then use to read and write using the other classes.
FileStream fs = File.Open(@"C:Filessample.txt", FileMode.Open);
We will see how to use the created file stream in a later lesson. The first overload of the Open method accepts the path of the file to open, and a value from the System.IO.FileMode enumeration. The file mode affects the behavior of the opened file. Indicating FileMode.Open means we are simply opening the file. We will see more about this enumeration in a later lesson.
Another overload accepts a third argument which is a value from the System.FileAccess enumeration. This parameter tells whether we want to read, write, or do both to the file we are opening. Again, this topic is best discussed when we reached the lesson on how to read and write files.