Saturday, January 29, 2011

Read Text File Line-by-Line in C#

Here is the code to read a text file from disk one line at a time into a string. This code ensures the file exists and properly closes the file if an exception occurs.

using System;
using System.IO;

namespace CSharp
{
class Program
{
static void Main( string[] args )
{
string filePath = @"c:\temp\test.txt";
string line;

if (File.Exists( filePath ))
{
StreamReader file = null;
try
{
file = new StreamReader( filePath );
while ((line = file.ReadLine()) != null)
{
Console.WriteLine( line );
}
}
finally
{
if (file != null)
file.Close();
}
}

Console.ReadLine();
}
}
}

No comments:

Post a Comment

Ajax CalendarExtender displaying at wrong position in Chrome

< script type ="text/javascript" language ="javascript">     function onCalendarShown(sender, args)...