File Class in C#

File Class in C# with Examples

In this article, I am going to discuss How to Implement File Handling using File Class in C# with Examples. Please read our previous article where we discussed How to Implement File Handling in C# using StreamWriter and StreamReader class with Examples.

File Class in C#

The File Class in C# provides some static methods to perform most of the file operations such as creating a file, copying and moving a file, deleting files, and working with FileStream to read and write streams. The File class is defined in the System.IO namespace.

There can be situations where you want to work with files directly. The basic file operations that we generally do are as follows:

  1. Reading: This operation is the basic read operation wherein data is read from a file.
  2. Writing: This operation is the basic write operation wherein data is written to a file. By default, all existing contents are removed from the file, and new content is written.
  3. Appending: This operation also involves writing information to a file. The only difference is that the existing data in a file is not overwritten. The new data to be written is added at the end of the file.

The File class in C# exposes many static methods for moving, copying, reading, writing, and deleting files. The File belongs to the System.IO namespace and if you go to the definition of the File class, you will find the following.

File Class in C# with Examples

File Class Methods in C#:

The following are commonly used methods of File class in C#.

  1. Copy: This method is used to Copies an existing file to a new file. Overwriting a file of the same name is not allowed.
  2. Create: This method is used to create or overwrite it in the specified path.
  3. Decrypt: This method is used to Decrypt a file that was encrypted by the current account using the System.IO.File.Encrypt(System.String) method.
  4. Delete: This method is used to delete the specified file.
  5. Encrypt: This method is used to encrypt a file so that only the account used to encrypt the file can decrypt it.
  6. Open: This method is used to Open a System.IO.FileStream on the specified path, having the specified mode with reading, write, or read/write access and the specified sharing option.
  7. Move: This method is used to Move a specified file to a new location, providing the option to specify a new file name.
  8. Exists: This method is used to determine whether the specified file exists.
  9. OpenRead: This method is used to open an existing file for reading.
  10. OpenText: This method is used to open an existing UTF-8 encoded text file for reading.
  11. OpenWrite: This method is used to open an existing file or create a new file for writing.
  12. ReadAllBytes: This method is used to open a binary file, read the contents of the file into a byte array, and then close the file.
  13. ReadAllLines: This method is used to Open a file, reads all lines of the file with the specified encoding, and then close the file.
  14. ReadAllText: This method is used to Open a text file, reads all the text in the file, and then close the file.
  15. ReadLines: This method is used to read the lines of a file.
  16. Replace: This method is used to replace the contents of a specified file with the contents of another file, delete the original file, and create a backup of the replaced file.
  17. WriteAllBytes: This method is used to create a new file, write the specified byte array to the file, and then close the file. If the target file already exists, it is overwritten.
  18. WriteAllLines: This method is used to create a new file, write the specified string array to the file, and then close the file.
  19. WriteAllText: This method is used to create a new file, write the specified string to the file, and then close the file. If the target file already exists, it is overwritten.
Example to Understand File Class in C#:

The C# Language and .Net Framework can work with files with the help of several methods of File class. Let us see how to use the File class methods to perform different file operations with some examples. Let us assume that we have a file in the D drive called MyFile.txt. The MyFile.txt file will be a simple text file and have 2 lines of data as follows:

Learn C#.NET By Dot Net Tutorials
C# is one of the Object-Oriented Programming Language

Example to Understand File Class in C#

Now, we will create a simple Console application and will work with File methods. In the console application, all code is going to write inside the program.cs class file.

Exists Method of File Class in C#

The Exists method of File Class in C# is used to check if a particular file is existing or not. This method will return true if the caller has the required permissions and the path contains the name of an existing file; otherwise, false. This method also returns false if the path is null, an invalid path, or a zero-length string. If the caller does not have sufficient permissions to read the specified file, no exception is thrown and the method returns false regardless of the existence of the path.

Now, let’s see the code which can be used to check if our MyFile.txt file exists or not. So, copy and paste the below code. The Exits is a static method of File class, so we are calling this method with the class name i.e. File. This method expects one parameter which is the file path.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\MyFile.txt";

            if (File.Exists(path))
            {
                Console.WriteLine("MyFile.txt File Exists in D Directory");
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exist in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

Here, first, we are storing the MyFile.txt file path in a string variable called path. Then, we use the Exists method to check if the file exists or not. If the File exists in the specified path, a true value will be returned.

If we get a true value then we write the message “MyFile.txt File Exists in D Directory” to the console window else If we get false then we write the message “MyFile.txt File Does Not Exist in D Directory” to the console window. So, when you run the above code, you will get the following output.

Exists Method of File Class in C#

ReadAlllines Method of File Class in C#:

The ReadAlllines Method of File Class is used to open a file and read all the lines one by one in the file and then close the file. The lines are then stored in a string array variable. Let us see an example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\MyFile.txt";

            if (File.Exists(path))
            {
                string[] lines= File.ReadAllLines(path);
                foreach(var line in lines)
                {
                    Console.WriteLine(line);
                }
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

In the above example, first, we are creating a string variable to store the file path. Then we are checking whether the file exists or not using the Exists method. If the file exists, then we are reading all the lines from the file by using the File.ReadAllLines method and store it in a string array. Then we are using a foreach loop to read all the lines one by one and print the same on the console window. As our file contains two lines of data, so when you run the above code, you will get the following output.

ReadAlllines Method of File Class in C#

ReadAllText Method of File Class in C#

The ReadAllText Method of File Class in C# is used to read all the lines in a file at once. The lines are then stored in a string variable. Let us see an example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"D:\MyFile.txt";

            if (File.Exists(path))
            {
                string lines= File.ReadAllText(path);
                Console.WriteLine(lines);
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

In the above example, first, we are creating a string variable called the path to store the file path. Then we are checking whether the file exists or not using the Exists method of File Class. If the file exists, then we are reading all the lines from the file at once by using the ReadAllText method of the File class and storing the result in a string variable. Then we print the same on the console window. When you run the above code, you will get the following output.

ReadAllText Method of File Class in C#

Copy Method of File Class in C#:

The Copy Method of File Class in C# is used to make a copy of an existing file. The most important point that you need to remember is Overwriting a file of the same name is not allowed using File.Copy method. The Copy method takes two parameters. The first parameter is the sourceFileName i.e. the file to copy and the second parameter is the destFileName i.e. the name of the destination file and the destination file cannot be a directory or an existing file. Let us see an example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string SourceFilePath = @"D:\MyFile.txt";
            string DestinationFilePath = @"D:\MyFile2.txt";

            if (File.Exists(SourceFilePath))
            {
                File.Copy(SourceFilePath, DestinationFilePath);
                string lines= File.ReadAllText(DestinationFilePath);
                Console.WriteLine(lines);
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

In the above example, first, we are creating two string variables called SourceFilePath and DestinationFilePath to store the source and destination file paths respectively. Then we are checking whether the source file exists or not using the File.Exists method. If the source file exists, we are calling File.Copy method to copy the source file MyFile.txt file to the destination file MyFile2.txt. Then we print the destination file data on the console window. So, when you run the above code, you will get the following output.

Copy Method of File Class in C#

Now you can see that MyFile2.txt should be created inside the D drive. The point that you need to remember is the destination file cannot be a directory or an existing file. For example, the MyFile2.txt file is already created inside the D drive, now again if you run the same code, you will get the following exception.

File Class in C# with Examples

There is another overloaded version of the Copy method available inside the File class with the following signature. You can pass the third parameter as true or false to override an existing file. So, the overloaded version of the Copy method is used to copy an existing file to a new file. Overwriting a file of the same name is allowed.

public static void Copy(string sourceFileName, string destFileName, bool overwrite);

So, let us modify the previous example and lets us use the overloaded version, and see the output.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string SourceFilePath = @"D:\MyFile.txt";
            string DestinationFilePath = @"D:\MyFile2.txt";

            if (File.Exists(SourceFilePath))
            {
                File.Copy(SourceFilePath, DestinationFilePath, true);
                string lines= File.ReadAllText(DestinationFilePath);
                Console.WriteLine(lines);
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}

Now, run the above application and you will not get any errors.

Delete Method of File Class in C#:

The Delete method of File Class in C# is used to delete an existing file. The Delete method of the File class takes one parameter which is the path of the file to be deleted. Let us see an example for a better understanding.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            string FilePath = @"D:\MyFile2.txt";

            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
                Console.WriteLine("MyFile2.txt File Deleted");
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

In the above example, first, we are creating a string variable called FilePath to store the file path. Then we are checking whether the file exists using the File.Exists method. If the file exists, we are calling File.Delete method passing the file path to delete file MyFile2.txt file. So, when you run the above code, you will get the following output.

Delete Method of File Class in C#

Create Method of File Class in C#

The Create Method of File Class in C# is used to create a file in the specified folder. There are multiple overloaded versions of this method is available in the File class. They are as follows:

  1. public static FileStream Create(string path): Creates or overwrites a file in the specified path.
  2. public static FileStream Create(string path, int bufferSize): Creates or overwrites the specified file. The bufferSize parameter specifies the number of bytes buffered for reads and writes to the file.
  3. public static FileStream Create(string path, int bufferSize, FileOptions options): Creates or overwrites the specified file, specifying a buffer size and a FileOptions value that describes how to create or overwrite the file.
  4. public static FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity): Creates or overwrites the specified file with the specified buffer size, file options, and file security.

Note: Please note that all the above-overloaded versions return an instance of FileStream class. So, we need to close the stream object by calling the Close method.

Let us understand Create method with an example. In the below example apart from the Create method, I am also using the WriteAllLines method which will write the data into the specified file.

using System;
using System.IO;
namespace FileHandlinDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Set the File Path
            string FilePath = @"D:\MyFile3.txt";

            //Create the File
            FileStream fs = File.Create(FilePath);
            fs.Close();

            if (File.Exists(FilePath))
            {
                //Writing Content to File
                string[] content = { "Hello", "And", "Welcome" };
                File.WriteAllLines(FilePath, content);
                Console.WriteLine("MyFile3.txt File Created with the Following Data");

                string fileContent = File.ReadAllText(FilePath);
                Console.WriteLine(fileContent);
            }
            else
            {
                Console.WriteLine("MyFile.txt File Does Not Exists in D Directory");
            }
            Console.ReadKey();
        }
    }
}
Code Explanation:

In the above example, first, we create a string variable called FilePath which we are going to create using the Create method. Then we are calling the Create method passing the FilePath which will create the MyFile3.txt file in the D drive and then immediately we close the FileStream object by calling the Close method. Then we are checking whether the MyFile3.txt file exists or not using the File.Exists method. If the MyFile3.txt file exists, then we are creating a string array and then calling the WriteAllLines method passing the FilePath and string array. This WriteAllLines method will write the string array data into the specified file. And finally, we are reading the content of the MyFile3.txt file and printing it on the Console. So, when you run the above code, you will get the following output.

Create Method of File Class in C# with Examples

In the next article, I am going to discuss TextWriter and TextReader Classes in C# with Examples. Here, in this article, I try to explain How to Implement File Handling using File Class in C# with examples. I hope you enjoy this File Handling using File Class in C# with Examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published.