Click to See Complete Forum and Search --> : Read last line of a text file


Korupt
August 23rd, 2008, 11:56 AM
Anyone have any idea how to make a StreamReader read the last line of a text file without knowing what it is. For example if I have a text file like this:

1
2
3
4
5
6
7

how can I make my program read the last line which is "7" but with out me telling the program that it is seven? Any help is appreciated thanks :)

verifier
August 24th, 2008, 01:30 AM
Maybe something like this:

int index = 1;
stream.Seek(0, SeekOrigin.End)
while(stream.ReadByte () != '\n')
{
stream.Seek(index, SeekOrigin.End)
++index
}

toraj58
August 24th, 2008, 01:39 AM
try this:


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

namespace streamreader
{
class Program
{
static void Main(string[] args)
{
StreamReader st = new StreamReader("test.txt");
string str = st.ReadToEnd();
int x = str.LastIndexOf('\n');
string lastline = str.Substring(x+1);
Console.WriteLine(lastline);
Console.ReadLine();
}
}
}


Touraj Ebrahimi [toraj_e] [at] [yahoo] [dot] [com]