System.IO.File Class Methods in C#

System.IO.File class provides static methods for creating, deleting, copying and opening a file, it returns FileStream object to work on.

File Class Methods

The following table explains the various static methods related to the System.IO.File class.

Method Name



Copies the specified file to the specified target path.


Creates the specified file.


Deletes the specified file.


Returns a Boolean value to see whether a file exists or not.


Returns an Object of Type System.IO.FileAttributes which contain information regarding the file such as whether it is hidden or not ....etc...


Retuns an object of type DateTime to represent the time of creation of the file.


Returns an object to type DateTime that represents the time of last access of the file.


Returns an object to type DateTime that represents the last write time of the file.


Moves the specified file to the specifed path.


Opens the specified file and returns the System.IO.FileStream Object for this file.


Opens the file for reading only and returns the System.IO.FileStream object of the file.


Opens the file for writing and returns a read / write System.IO.FileStream object of the file.


Accepts an Object of type System.IO.FileAttributes which contain different information regarding file and set these attributes to the file.



The code below shows usage of the common static methods in File class.

    //Create File

    //Copy a file
    File.Copy("C:\\File1.txt", "C:\\Temporary\\File1.txt");

    //Checking the existence of a file
    if (!File.Exists("C:\\File1.txt"))

One can also copy a file and overwrite it if the file already exists using an overload of the copy method as shown below.

    File.Copy("C:\\File1.txt", "C:\\MyFolder\\File1.txt", true);

The Boolean parameter in the above overload conveys to the copy method to overwrite if the file already exists.

ReadAllLines Method

In the following example, we read all the lines of a file using the File.ReadAllLines method, this method returns a String array of each line in the file, which is converted to a List and then we iterate over the list to print all the lines read from the file.

    List<string> fileLines = File.ReadAllLines("file.txt").ToList();

    foreach (string obj in fileLines)