012 – C# – Developing the application of reading and writing text files. Classes StreamReader and StreamWriter.


Developing the application of reading and writing text files. Classes StreamReader and StreamWriter.

 In the application is demonstrated using of classes StreamReader and StreamWriter for reading and writing the text files.

 Also, in the application are used controls (components) RichTextBox and OpenFileDialog.


The task

 Develop the application of reading/writing text files. The application should be able to select the file for reading, correct it and write to the drive.



  1. Run MS Visual Studio.

 Create the project as Windows Forms Application. Save the project under any name.


  1. Building the form of application.

Create the form as shown in Figure 1.

The following controls are placed on the form:

– two controls of type “Button”. Automatically will be created two objects named “button1” and “button2”;

– one control of type RichTextBox. The object named “richTextBox1” will be created;

– control of type Label. The object with name label1 is created.

02_02_00_012_01_Fig. 1. The controls of application form

 Set up the controls of type “Button” as follows:

– in the control “button1” property Text = “Open file“;

– in the control “button2” property Text = “Save the file“.

Setting up of form Form1 of application:

– property Text = “Reading/writing of text files“;

– property MaximizeBox = false;

– property FormBorderStyle = “Fixed3D”;

– property StartPosition = “CenterScreen”.

 Also, you need to correct  the size of form and controls on the form as shown in Figure 2.

In the control RichTextBox (Figure 3):

– property WordWrap = “false” (wrap the long strings within the borders of the editor window).

 The control “RichTextBox” is a multiline editor, that works with text in RTF format. Text in RTF format saves additional service information, which manages by the properties of each paragraph and change the font in the text.

02_02_00_012_02eFigure. 2. The form of application after correcting and setting up of properties

02_02_00_012_03eFig. 3. The control RichTextBox


  1. The control OpenFileDialog.

 To select the text file for reading, you need to use the control of type OpenFileDialog. This control is a standard dialog box for open the files.

 Place on the form the control OpenFileDialog (Fig. 4).

02_02_00_012_04eFig. 4. The control OpenFileDialog


  1. Adding the internal variables into the text of application.

 For work of program you need to input the following additional internal variables:

f_open – determines, whether the user chose the command “Open File …“;

f_save – determines, whether the file was saved.

 Therefore, in the text of “Form1.cs” you need to type the following code:


namespace WindowsFormsApplication1
    public partial class Form1 : Form
        bool f_open, f_save; // determines the selection of the file and it saving

        public Form1()



  1. Programming the event “Load” of class of form Form1.

 Event “Load” occurs when the form is loaded immediately after the application starts to run. In the event handler is recommended to include the initial initialization of variables.

 In this case, the initial initialization is realized for such variables and objects as f_open, f_save, label1, richTextBox1.

 In the component label1 will be showed path to the file. In the component richTextBox1 will be displayed the content (text) of selected file.

 Listing of method Form1_Load() of event “Load” of loading the form is following:

private void Form1_Load(object sender, EventArgs e)
  f_open = false; // file not opened
  f_save = false;
  label1.Text = "-";
  richTextBox1.Text = "";


  1. Import of namespace System.IO.

 In this paper to read and write files will be used the opportunities of StreamWriter and StreamReader classes from the C# class library.

 Therefore, to use the methods of these classes, is needed to add the string at the beginning of module “Form1.cs”:

using System.IO;

So, the top part of file “Form1.cs” is following:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO;

  1. The event programming of click on the button1 (“Open file …”).

  To call a standard window of selecting the file, user need to select the command “Open file …(button1). An example of programming of event of click on the button “button1” is described here in details.

 Listing of handler button1_Click(), that opens the window of selecting the file is following:

private void button1_Click(object sender, EventArgs e)
  // 1. Opening the window and checking whether file is selected
  if (openFileDialog1.ShowDialog() == DialogResult.OK)
    // 2. Show the name of file on the form in component label1
    label1.Text = openFileDialog1.FileName;

    // 3. Set the flags f_open and f_save
    f_open = true;
    f_save = false;

    // 4. Read the file in richTextBox1
    // clear the following text in richTextBox1

    // 5. Create the object of class StreamReader and read data from file
    StreamReader sr = File.OpenText(openFileDialog1.FileName);

    // additional variable for reading of string from the file
    string line = null;

    line = sr.ReadLine(); // reading of first string

    // 6. The cycle of strings reading from a file
    while (line != null)
      // 6.1. Add a string in richTextBox1

      // 6.2. Add a new line

      // 6.3. Read the previous string
      line = sr.ReadLine();

    // 7. Close the connection to the file

 To call a standard window of selecting the file is used method ShowDialog() of component openFileDialog1. The selected file is saved in the property FileName of object openFileDialog.

 To read a text file is used class StreamReader, which realizes reading of symbol data from the file. To create an instance of class StreamReader is used method OpenText() from class File. Class File includes several methods, which are very good for simplify reading of symbol data.

 To read the string from file, in the program is used method ReadLine(), which reads the symbol string from current stream and which returns data as a string. If the end of the file, the method returns null.

 Reading of strings is carries out in the local variable line.

 To add a string in the object richTextBox1, you need to use method AppendText().


  1. Programming the event of changing the text in component RichTextEdit.

 In accordance with the logic of the program, if changes occur in the text file, then f_save flag should be equal to the value false.

 In the component richTextBox1 there is the event TextChanged, which is called when text changes in the editor (Fig. 5).

02_02_00_012_04eFig. 5. The event TextChanged of control richTextBox1

 Event handler of the event TextChanged has the following view:

private void richTextBox1_TextChanged(object sender, EventArgs e)
  f_save = false;


  1. Programming an event of clicking on the button “Save the file”.

  To save the changed text into a file, you need to select command “Save the file” (button2). To save the file, which was changed in richTextBox1, are used methods from class StreamWriter.

 Listing of event handler of clicking on the button2 is following:

private void button2_Click(object sender, EventArgs e)
  // 1. Check whether the file is opened?
  if (!f_open) return;

  // 2. If the file is opened, the checking - whether it is saved.
  if (f_save) return;

  // 3. Creating an object of type StreamWriter and getting the string data
  StreamWriter sw = File.CreateText(openFileDialog1.FileName);

  // 4. Reading of strings from richTextBox1 and adding their into the file
  string line;

  for (int i = 0; i < richTextBox1.Lines.Length; i++)
    // 4.1. Reading the string
    line = richTextBox1.Lines[i].ToString();

    // 4.2. Adding the string into a file

  // 5. Close the object sw

Let’s explain some code snippets.

 First of all, in the event handler button2_Click, is checked whether file is opened. Then is created the object (variable) with name “sw” of type StreamWriter.

 When the object is created,  is used method CreateText() from class “File”. This method returns an instance of type StreamWriter. The file name is saved into the property openFileDialog1.FileName.

 For access to the entered strings is used the property Lines of component richTextBox1, which is an array of strings.

 To add a single string, you need to call method WriteLine() of object sw of type StreamWriter.