Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | ASP.NET 2.0 Tutorials | Web Services | How Do I...? | Class Browser | WPF Quick Starts | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET » TextReader and TextWriter in C#

TextReader and TextWriter in C#

This article covers the information of how to read or write (Unicode) character based data through TextReader and TextWriter.

Author Rank :
Page Views : 21925
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

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.

StreamWriter and StreamReader

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.

  1. close() -- Closes the Writer and frees any associated resources.
  2. Write() -- Writes a line to the text stream, with out a newline.
  3. WriteLine() -- Writes a line to the text stream, with a newline.
  4. 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 int Main(sting[] args)
{
FileInfo t =
new FileInfo("Arungg.txt");
StreamWriter Tex =f.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.

  1. Read() -- Reads data from an input stream.
  2. ReadLine() -- Reads a line of characters from the current stream and returns the data as a string.
  3. 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;
}
}

In the above class Readtextfile I open the text file Arungg.txt and read the contents using the ReadLine() method. In both StreamReader and StreamWriter are concerned with moving text data to and from a specified file.

StringWriter & StringReader

Using the StringReaders and StringWriters can treat textual information as a stream of in-memory characters. In this we can insert or remove string between a block of textual data.

Let us see a program in which I add and delete some string between a block of text.

public class stringwrite
{
public static int Main(string[] args)
{
StringWriter wr =
new StringWriter();
wr.WriteLine("Friendship is not a two way road.");
wr.WriteLine("It is a one way road travelled by two people.");
wr.Write(Writer.NewLine);
wr.close();
Console.WriteLine("Data: {0}",wr.ToString());
return0;
}
}

Running the above program we get the textual data in the console.

The output:

Data:
Friendship is not a two way road.
It is a one way road travelled by two people.

Press any key to continue

Now I show you how to insert and delete some string between textual data.

using System.Text;
public class stringwrite
{
public static int Main(string[] args)
{
StringWriter wr =
new StringWriter();
wr.WriteLine("Friendship is not a two way road.");
wr.WriteLine("It is a one way road travelled by two people.");
wr.Write(Writer.NewLine);
wr.close();
StringBuilder bu = wr.GetStringBUilder();
string entiredata = bu.ToString();
Console.WriteLine("The data:{\n0}",entiredata);
// TO ADD SOME STRING.
bu.Insert(45,"together-hand in hand");
entiredata = bu.ToString();
Console.WriteLine("The modified data:\n{0}",entiredata);
// TO REMOVE SOME STRING.
bu.Remove(45."together-hand in hand".Length);
entiredata = bu.ToString
Console.WriteLine("The original data:\n{0}",entiredata);
return 0;
}
}

In the above program I write some character data to a StringWriter type and modify the data by inserting some item to buffer at position 45.After inserting I also show how to remove some particular string from the data.

The Output:

The Data:
Friendship is not a two way road.
It is a one way road travelled by two people.

The modified data:
Friendship is not a two way road.
It is a one way road travelled by two people together-hand in hand.

The original data:
Friendship is not a two way road.
It is a one way road travelled by two people.

Now Let us see how to use StringReader to read a block of character data rather than a entire file.

StringReader re = new StringReader(wr.ToString());
string input = null;
while(( input = re.ReadLine()) != null)
{
Console.WriteLine(input);
}
re.close();

Like the above way by using StringReader we can read data from a file.

Conclusion

I hope after reading this article , the user has gained some information about how to create,write and read in a text file using TextReader and TextWriter in C# and also something about Friendship!.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
G Gnana Arun Ganesh
G.GNANA ARUN GANESH, an ECE graduate (1997-2001) seeking a profession in either Software or Hardware Company. During Campus interview selected as a Software Engineer at GREEN MICRO SYSTEMS Chennai, a German collaboration company. Due to down stream in software market they have cancelled the offer. His skills includes VB, COM/DCOM, ASP, VB.NET, C# and Embedded systems. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.