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

Explanation

Copy()

Copies the specified file to the specified target path.

Create()

Creates the specified file.

Delete()

Deletes the specified file.

Exists()

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

GetAttributes()

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

GetCreationTime()

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

GetLastAccessTime()

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

GetlastWriteTime()

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

Move()

Moves the specified file to the specifed path.

Open()

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

OpenRead()

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

OpenWrite()

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

SetAttributes()

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
    File.Create("C:\\File1.txt");

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

    //Checking the existence of a file
    if (!File.Exists("C:\\File1.txt"))
    {
        File.Create("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)
    {
        Console.WriteLine(obj);
    }