INTRODUCTION:
This article covers the information of how to read or write (Unicode) character based data through TextReader and TextWriter. The TextReader and TextWriter are base classes. The StreamReader and StringReader derives from the abstract type TextReader. Similarly the StreamWriter and StringWriter derives from the abstract type TextWriter.
STREAMWRITERS and STREAMREADERS:
As I mentioned earlier StreamWriter type derives from a base class named TextWriter. This class defines members that allow derived types to write textual data to a given character stream.
Let us see some of the main members of the abstract class TextWriter.
- close() - Closes the Writer and frees any associated resources.
- Write() - Writes a line to the text stream, with out a newline.
- WriteLine() - Writes a line to the text stream, with a newline.
- Flush() - Clears all buffers.
WRITING - TEXT FILE:
Let us see the Writing to a Text File with a example.
Before we move into writing to a text file we have to know about "FileInfo" class. What is FileInfo? In the framework of .NET, the system.IO namespace is the region of the base class libraries devoted to file-based input and output services.File Info is one of the core type of System.IO Namespace.
The function of the FileInfo is to encapsulate a number of details regarding existing files on your hard drive (size,file attributes,creating time,etc.)as well as aid in the creation and destruction of new files. Let us move to example.
In this example in the Writetextfile class I create a file named "Arungg.txt" using the FileInfo class. After creating the text file using the CreateText() method, I get a StreamWriter and write some textual data to the newly created text file. We can also add numeric data into the text file.
public
class Writetextfile{
public static void Main(string[] args)
{
FileInfo t = new FileInfo("Arungg.txt");
StreamWriter Tex =t.CreateText();
Tex.WriteLine("Arungg has launced another article");
Tex.WriteLine("csharpheaven is the new url for c-sharpcorner");
Tex.Write(Tex.NewLine);
Tex.close();
Console.WriteLine(" The Text file named Arungg is created ");
}
} If you open the text file the data is entered there.
READING - TEXT FILE:
Now let us see how to read a text file using the StreamReader type.
Let us see some of the main members of the abstract class TextReader.
- Read() -- Reads data from an input stream.
- ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.
- ReadToEnd() -- Reads all characters to the end of the TextReader and returns them as one string.
public class Readtextfile
{
public static int Main(string[] args)
{
StreamReader re = File.OpenText("Arungg.txt");
string input = null;
while ((input = re.ReadLine()) != null)
{
Console.WriteLine(input);
}
re.close;
return 0;
}
}
gauravPosted Dec 17, 2012, 9:14 AM
this is really nice bro i have completed my one application through by your notes"' thanks alot