Search:

Custom Search
_________________________________________________________________

Sunday, April 20, 2008

Text file Reading and Writing in C#

This program below demonstrates the use of StreamWriter and StreamReader (both derive form the abstract type TextWriter and TextReader respectively). The .Net Framework has simple solutions to work with files. When working with text files there are usually three common steps:

1- Opening the file
2- Reading/Writing
3- Closing it

Now, lets take a look at this example:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace ConsoleApplication
{

class Program
{

public static void Main(string[] args)
{

//C# Code for writing into a file we call: File.txt

FileInfo f = new FileInfo("File.txt");
StreamWriter Text = f.CreateText();

//Insert text in separate lines
Text.WriteLine("-->Line One content");
Text.WriteLine("--->Line Two Content");

//Insert text but does not create a new line
Text.Write("---->Line Three ");
Text.WriteLine("Content");

//To create new Line.
Text.Write(Text.NewLine);
Text.WriteLine(System.DateTime.Now);
Text.Close();

//Calling the method to read File.txt
readFiles();

Console.Read();


}
public static void readFiles()
{

//We open File.txt
StreamReader sr = new StreamReader("File.txt");
string lines = null;

//Here we do a while loop in order to look for none empty lines.
while ((lines = sr.ReadLine()) != null)
{
Console.WriteLine(lines);
}

sr.Close();
}

}
}

No comments: