Friday, January 20, 2012

StreamReader and StreamWriter in .Net (C#)



StreamReader and StreamWriter classes are available in System.IO namespace. StreamWriter class used to write text (string) in file. StreamWriter class inherits from abstract TextWriter class. StreamReader class used to read text (string) from file. StreamReader class inherits from abstract TextReader class. 


Below are some useful methods of StreamReader and StreamWriter class.

Methods
Description
StreamWriter.Write
Writes text to file.
StreamWriter.WriteLine
Writes text to file, followed by line terminator.
StreamReader.Read
Reads text from file.
StreamReader.ReadLine
Reads line from file.

Read/Write text to file using StreamWriter.WriteLine and StreamReader.ReadLine

string[] names = new string[] { "Mitesh", "Jayesh", "Pritesh", "Kalpesh" };
void ReadWriteText()
{
    //write names to test.txt file
    using (StreamWriter sw = new StreamWriter(@"d:\Temp\Test.txt"))
    {
        foreach (string name in names)
            sw.WriteLine(name);
    }

    //read names from test.txt file
    using (StreamReader sr = new StreamReader(@"d:\Temp\Test.txt"))
    {
        string name = string.Empty;
        while ((name = sr.ReadLine()) != null)
        {
            Console.WriteLine(name);
        }
    }
}

Output –

Read/Write text from file using StreamReader.ReadLine and StreamWriter.Write


void ReadWriteText()
{
//write string/charactors to test.txt file
using (StreamWriter sw = new StreamWriter(@"d:\Temp\Test.txt"))
{
    foreach (char character in "Hello World!")
        sw.Write(character);
}

//read string/charactors from test.txt file
using (StreamReader sr = new StreamReader(@"d:\Temp\Test.txt"))
{
    string name = string.Empty;
    while ((name = sr.ReadLine()) != null)
    {
        Console.WriteLine(name);
    }
}
}

Output –

No comments:

Post a Comment