Click to See Complete Forum and Search --> : Best way to read from a text file by specifying line number


doglin82
November 17th, 2007, 09:48 PM
Hi :
If I need to read a certain Line from a txt file, is there an existing API that would let you specify the number of line that you want to read from, and just read it?

or you have to traverse through the entire content by yourself???

please let me know


THanks

dglienna
November 17th, 2007, 10:33 PM
Read it and then split it, based on the line count.

using System;
using System.IO;

class Test
{

public static void Main()
{
string path = @"c:\temp\MyTest.txt";

try
{
if (File.Exists(path))
{
File.Delete(path);
}

using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}

using (StreamReader sr = new StreamReader(path))
{
//This allows you to do one Read operation.
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}