C# File Read Write Example


In this article, I will describe the process of reading and writing text files. To perform these operations, we first add the projected System.IO library.

This library will make us realize our actions on the files. If you are new to programming and do not know how to add a library to your project, just write the above code in the image.

Now that we have added our System.IO library, we can now write and read files.

The tools we will add to the project after we open the form work environment are;

  • 2 buttons to perform read and write commands.
  • We use richTextBox to display the file or to write the text to record.
  • OpenFileDialog to select the address of the file to read.
  • The saveFileDialog to determine where the file to write is written.

 

First I will start with the reading process. We will use the StreamReader class for reading. When defining the StreamReader class we need to input the string parameter, ie the path of the file. You will use the openFileDialog tool mentioned above to locate this file path, or you can write the file path yourself without using this tool.

Let’s write the following codes in the Read button, and I’ll explain what the codes do.

  • ShowDialog will help us to open our tool named openFileDialog1.
  • We created a StreamReader class with a name of read and we entered the address (FileName) of the file we would select with the openFileDialog tool as a parameter.
  • We print the contents of the file we selected in the richTextBox we created for reading or writing the file.
  • ReadLine () is used to read the file line by line.
  • Then we close the arrow link to keep the program busy.

This is the end of our reading process. There is a write in queue.

We will use the StreamWriter class for writing. When defining the StreamWriter class we also need to input string parameters. You will use the saveFileDialog tool mentioned above to select this file path, you can write the file path yourself without using this tool.

Write the following codes in the summer button, and I will explain what the codes are doing, as above, one by one.

  • With DefaultExt we automatically print the extension of the file we will save.
  • With FileName we determine the name of the file to save.
  • ShowDialog will work for saveFileDialog to work.
  • we created a StreamWriter class with the name summer and we specified the address of the place we chose with saveFileDialog.FileName as the parameter.
  • We use WriteLine to save the text inside the richTextBox. WriteLine writes in each line.

General Code

 

Demo

 

if you have question do not forget to write from the chat button next to it or from the comment

You may also like...

Leave a Reply

Your email address will not be published.