Go to DotNetFunda.com
 Welcome, Guest!  
LoginLogin  
{ Submit content and get exposure !!! }
Submit: Article | Interview Question | Tips | Joke | Question | Link || Search  
 Skip Navigation Links Home > Articles > Reading and Writing Text Files

All Articles | Post Articles |  Subscribe to RSS

Reading and Writing Text Files

 Posted on: 7/23/2008 1:20:05 AM by Majith | Views: 427 | Category: C# | Level: Intermediate | Print Article
ASP.NET Hosting with Windows 2008/2003
Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy.


Reading and writing in text files

Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:

  1. Open the file
  2. Read/Write to the file
  3. Close the file

It's that simple.  Listing 1 shows how to write text data to a file.

Writing to a Text File

Listing 1: Writing Text Data to a File: TextFileWriter.cs

using System;
using System.IO;

namespace csharp_station.howto
{
    class TextFileWriter
    {
        static void Main(string[] args)
        {
            // create a writer and open the file
            TextWriter tw = new StreamWriter("date.txt");

            // write a line of text to the file
            tw.WriteLine(DateTime.Now);

            // close the stream
            tw.Close();
        }
    }
}

This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:

The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:

            TextWriter tw = new StreamWriter("date.txt");

Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:

            tw.WriteLine(DateTime.Now);

When you're done writing to the file, be sure to close it as follows:

            tw.Close();

Reading From a Text File

Listing 2 shows how to read from a text file:

Listing 2: Reading Text Data from a File: TextFileReader.cs
using System;
using System.IO;

namespace csharp_station.howto
{
    class TextFileReader
    {
        static void Main(string[] args)
        {
            // create reader & open file
            Textreader tr = new StreamReader("date.txt");

            // read a line of text
            Console.WriteLine(tr.ReadLine());

            // close the stream
            tr.Close();
        }
    }
}

In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:

            Textreader tr = new StreamReader("date.txt");

Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:

            Console.WriteLine(tr.ReadLine());

When done reading, you should close the file as follows:

            tr.Close();

 


Interesting?  Bookmark and Share kick it on DotNetKicks.com


About Majith B

Experience:3 year(s)
Home page:
Member since:Friday, July 18, 2008
Biography:
 Latest post(s) from Majith

   ◘ Java Script GridView ClientSide Validation posted on 9/30/2008 12:22:12 AM
   ◘ Diff Between DataGrid and GridView posted on 9/17/2008 11:20:35 PM
   ◘ Dynamic Single click , Double Click for Editing the rows in Gridview posted on 9/10/2008 11:44:57 PM
   ◘ Applying Themes and Skins using ASP.NET ,C# posted on 8/21/2008 3:24:56 AM
   ◘ Dynamic Menu using XML DataSource ASP.NET ,VB.NET posted on 8/6/2008 10:55:31 PM


Response(s) to this Article
Posted by: Raja | Posted on: 23 Jul 2008 04:09:16 AM
Hey Majith,

Your article looks good but you must use either try catch finally or using statement with TextReader or TextWriter object otherwise if any error occurs while writing or reading that object will NOT be closed and disposed and that will create problem in writing or reading any text file in future for that session and unnecessary memory will be occupied in the server.

so your modified code should look like

          // create a writer and open the file

TextWriter tw = new StreamWriter("date.txt");
try
{
// write a line of text to the file
tw.WriteLine(DateTime.Now);
}
catch
{
// you can log or throw the error
throw;
}
finally
{
// close the stream
tw.Close();
}

Same applies to TextReader object too.

Thanks


About Us | Contact Us | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
All rights reserved to DotNetFunda.com. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
(Best viewed in IE 6.0+ or Firefox 2.0+ at 1024 * 768 or higher)