StreamReader read last line in a text file

  • Thread starter Thread starter Tarren
  • Start date Start date
T

Tarren

Hi:

I want to check my text file to ensure the last line has only DONE on it,
prior to loading the file.

How can I do this with a StreamReader object to go to the last line so I can
perform the string comparison?

Thanks
 
If i understand you correctly i would do it like this:

StreamReader f = new StreamReader(fileName);


ArrayList lines = new ArrayList();

string line;

while ((line = f.ReadLine()) != null )

{

lines.Add(line);

}

f.Close();

Then you move to the last index in ArrayList and tests for the word DONE

Best regads

Trond
 
Hi Tarren,

Besides reading all the info like Trond said, if you know that there is nothing after DONE (like line breaks or tabs etc) you could set the StreamReader's position to last position -4

using(FileStream fs = File.OpenRead("c:\\file.dat"))
{
using(StreamReader sr = new StreamReader(fs))
{
sr.BaseStream.Position = fs.Length - 4;
if(sr.ReadToEnd() == "DONE")
// match
}
}
 
Back
Top