File Handling In C#

Introduction

As the name File Handling is self-explanatory which means handling a file. File handling refers to managing a file in different ways. With the concept of file handling, we can perform different operations like creating a file, writing in a file, reading from a file, updating a file, and deleting a file. Let's deep dive into the concept.

What is a File? 

We store our data in a single unit in our computer system that unit is known as a file. A file is like a container that stores our data. Files can be of different types depending upon the type of data that we are storing.

What is Stream?

When we perform reading and writing operations on a file it becomes a stream. It is a sequence of bytes moving from one place to another place and used for communication. 

Visual Representation of the flow of classes 

In the above diagram, we have the Object class which is the parent class of all classes in C#. Inside the System.IO namespace, we have FileSystemInfo, File, Path, Directory, and DriveInfo. File, Path, and Directory classes have static methods, which means we do not have to create objects of these classes we can directly call methods of these classes by the class name itself. FileInfo, DirectoryInfo, and DriveInfo contain instance methods. We need to create objects of these classes to call the methods of these classes. All the predefined classes of file handling come under the System.IO namespace therefore first we need to use the System.IO namespace at the top of the code. Let's understand the objective of each class in the System.IO namespace.

Classes Description
Directory It is used for managing a directory.
DirectoryInfo It is used to perform operations on directories.
DriveInfo It gives the information drives.
File It is used to perform operations on a file.
FileInfo It gives us the information of the existing file.
Path It gives us the path information.
BinaryReader It reads data from a binary stream.
BinaryWriter It writes the data into a binary to a stream.
StreamReader It is used for reading characters from a byte stream.
StreamWriter It is used for writing characters to a stream.

Implementing File Handling Operations

Notepad in our computer system is the best practical example of file handling. We do multiple operations in notepad on a single file. In this article, we will create a prototype of a notepad and will implement many operations.

Operations we will perform 

  • Creating a new file
  • Reading from the file
  • Updating an existing file and
  • Deleting a file.

Prerequisites

  • Create a design of a notepad using window forms.
  • From the toolbox add an Open and Save As dialog box.

Your design should look like the below-given image.

notepad design

In the above image, we have added first a MenuStrip and in the middle, we have a TextBox. We have also added an Open and Save As dialog. Let's start with the first operation.

1. Creating a new file

To create a new file firstly we need to double click on the Open as shown in the image below:

creating new file

After that, we will be redirected to the coding file. In that file write code as shown below:

private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
    string path = @"D:\\newfile.txt";    //path with name of the file you want to create
    File.Create(path);                   //File.Create() used to create the file
    MessageBox.Show("File Created Successfully");
}

In the above code, the path variable stores the location and name of the file in string format. Then we applied the Create method of the File class to create a new file. MessageBox.Show will display a message to confirm the creation of a file.

Output

Output creating new file

In the above image, we can see a message of confirmation.

2. Reading from the file

In this operation, we will see how we can read an existing file in our computer system. To read a file we need to double click on Open as shown in the image below:

reading file

As we already have an OpenFileDialog which will provide an interface and path of the file. After clicking on Open we will write the following code.

private void openToolStripMenuItem_Click(object sender, EventArgs e) {
    if (openFileDialog1.ShowDialog() == DialogResult.OK) {
        textBox1.Text = File.ReadAllText(openFileDialog1.FileName); //ReadAllText() method 
        //is used to read file 
    }
}

In the above code, inside the openToolStripMenuItem_Click function if we click on the open in Dialog. Inside if condition ReadAllText method of File class is used to read data of a file. We are displaying the data of the file in the textbox. openFileDialog1.FileName will read the path and name of the file and return to the ReadAllText method.

Output

1. We will select the file want to read and click on Open 

output open file

2. After that you can see the data inside the file. The file demoOne.txt is open now.

output open file

3. Writing into the file

To write into a file we need to double click on the Save As option as given below:

writing into file

After that we have to write the code given below:

private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
    DialogResult dres = saveFileDialog1.ShowDialog();
    if (dres == DialogResult.OK) {
        File.WriteAllText(saveFileDialog1.FileName, textBox1.Text); //this will update the 
        //text into the file
    } else if (dres == DialogResult.Cancel) {
        saveFileDialog1.Dispose();
    }
}

In the above code, saveAsToolStripMenuItem_Click is a click function. If we click on the Save then the if-condition will be executed. Inside if we have File class and WriteAllText method write the text into the file. saveFileDialog1.Filename provides the path and name of the file. texBox1.Text will give all text of the textBox1 that we want to write in our file.

Output

In the previous operation, we opened a file named demoOne.txt Now we will update the text of this file using the WriteAllText method of the File class. In the below image we have updated the text of the file.

output save as file

Now we will click on the File option in the top left corner and click on Save As as shown in the image below.

output save as

It will open a SaveFileDialog and as given below:

output save as

Here select the file name or click on Save. Your file has been updated now.

4. Deleting a file

To delete a file double click on the Delete option as given below:

delete file

After that, you will be redirected to the coding part. Write the code given below to delete a file

private void deleteToolStripMenuItem1_Click(object sender, EventArgs e) {
    string filepath = openFileDialog1.FileName;
    File.Delete(filepath); //File.Delete() is used to delete a file
    textBox1.Text = String.Empty;
    MessageBox.Show("File Deleted Successfully");
}

In the above code, deleteToolStripMenuItem1_Click is a delete click function. We have stored the path in the filepath variable from openFileDialog1.FileName. Now, run the Delete method of the File class. After deleting the file it will show a confirmation message as given in MessageBox.Show.

Output

In the previous operation, we opened a file demoOne.txt. Now click on the File option at the top left corner and click on Delete.

output delete file confirmation

We can see a confirmation message here. The file has been deleted.

We have done four important and mostly used file operations here. There are a lot of file managing operations like copying a file, Moving a file, and a lot more. You can refer to the official documentation from here.

Article in a nutshell

  1. File handling refers to managing a file in different ways.
  2. When we perform reading and writing operations on a file it becomes a stream.
  3. Create() method is used to create a new file.
  4. ReadAllText() method is used to read a file.
  5. WriteAllText() method is used to write in a file.
  6. Delete() method is used to delete a file.

Thanks for reading this article. I hope you learned about file handling.


Recommended Free Ebook
Similar Articles