Wednesday, November 6, 2013

Stream Reader and Stream Writer in c#

           In this article, we are going to see how to use StreamReader and StreamWriter to read and write data in files

StreamReader:

                To load text from file to string you can use StreamReader.Re­adToEnd method. First create new instance of StreamReader. As a parameter in constructor you can pass string with file path or Stream instance. Default encoding is UTF-8.

                Widely used methods in StreamReader class are,

1)Read() : Reads single character.
2)ReadLine() : Reads single line.3)ReadToEnd() : Reads full file.

Example:

using (StreamReader reader = new StreamReader("file.txt"))
                {
                    string line= reader.ReadLine();
                    while (line  != null)
                    {
                                Console.WriteLine(line); // Write to console.
                                line= reader.ReadLine();
                    }
                }

For more info refer to StreamReader in c#

StreamWriter:

                In order to write a text or data into a file, StreamWriter Class can be used. It supports two main methods to write an input into the file.

1. Write(): It is used to write a text of continuous without line break break into the file.                       Pharagraph texts can be used with that method.
2. WriteLine(): To write a text with line break.

Example demonstrates following logical steps for writing text into a File using FileStream Class Instance.

Example:

using (StreamWriter writer = new StreamWriter ("file.txt"))
                {
                    string line= “test write”;
                    writer.Write("test");
                    writer.WriteLine(line);                  
                }
For more info refer to StreamWriter in c#

No comments:

Post a Comment