Monday, April 28, 2008

How to Read/Write a text file in C#

Text files are used in most of the applications to store data, configuration etc. A developer often has to either read a text file or write some data to a text file. Microsoft .NET has provided easy access features that can be used for reading and writing a text file. There are three basic steps in reading or writing a text file:

1. Open a text file.

2. Read/Write the text file.

3. Close the text file.

In the step 1, we identify the text file that we want to operate on. Then we open the file using the objects of predefined classes provided by .NET. Once the file is opened, we are free to operate on it. After the completion of the operation i.e. read/write we should close the file so as to free the resources (Memory, File connection etc) occupied for performing the operation.

Below is the C# code that uses the above given principle to READ the text file and display it on the console output:

using System;

using System.IO;

namespace HowToReadATextFile

{

class FileReader

{

static void Main(string[] args)

{

// Create reader & open the file

Textreader tReader = new StreamReader("Sample.txt");

// Read a line of text

Console.WriteLine(tReader.ReadLine());

// Close the File Stream

tReader.Close();

}

}

}

Writing to a text file:

using System;

using System.IO;

namespace HowToWriteToATextFile

{

class FileWriter

{

static void Main(string[] args)

{

// Create a writer and open the file.

TextWriter tWriter = new StreamWriter("Sample.txt");

// Write a line of text to the file

tWriter.WriteLine("Sample text inside the Sample.txt file!!");

// Close the stream

tWriter.Close();

}

}

}

/////////////////////////////////////////////////////////////////////////////////////

2 comments:

Anonymous said...

hai,
how to read and write a text file in c#. please tell me...

Anonymous said...

how to update a file?

Post a Comment