Friday, September 21, 2012

Beginner in C#: using StreamReader and StreamWriter

Brief Definition

StremReader: used to Read data from a file, such as .txt files.
StremWriter: used to Write data on a file, or even create a new file.

Example

To make things simple lets consider a simple example.
We want to write a C# console application that will EDIT a text file.
The process is as the following:
  1. Reading the old text file
  2. Writing a new one (edited one)
  3. Deleting the original.
Before you start make sure you've added this line above the namespace:
using System.IO;
In the following we suppose that you have a text file in the Debug directory of your project with name "file.txt".

Declarations:
            StreamReader sR = new StreamReader("file.txt");
            StreamWriter sW = new StreamWriter("new.txt");

Writing data in the new.txt file while reading from the file.txt file at the same time.
            while (sR.Peek() != -1) // stops when it reachs the end of the file
            {
                string line = sR.ReadLine();
                // "line" EDITING GOES HERE
                sW.WriteLine(line); // writing the edited line as a new line in the new.txt file
            }

Deleting the old file and rename the new file as the old file's name.
            File.Delete("file.txt");
            File.Move("new.txt", "file.txt");

Finally close the initially declared StreamReader and StreamWriter.
                sR.Close();
                sW.Close();
And that's it! leave your comments.