Newbie question - gotta love them...return last line of a textfile

  • Thread starter Thread starter kaiser
  • Start date Start date
K

kaiser

Hello people

How do i return the last line of a text file to a string? I am only
interesed in the value of the last line, none of the other lines.

Tx
 
Hi,

Iterate in it and keep the last line, plain and simple

There is no shortcut, if that is what you was looking for


cheers,
 
Two ways:

(a) Open the file and read every line (Try File.OpenText and file.ReadLine)
and just remember the last line
(b) Or if the file is huge (or just for fun) open the file, seek to the end
of it, and read it backwards (make sure you choose a large enough buffer)
and read it until you find '\n' or "\n\r" and then return the string from
that point forward.
 
Hi,

(b) Or if the file is huge (or just for fun) open the file, seek to the
end of it, and read it backwards (make sure you choose a large enough
buffer) and read it until you find '\n' or "\n\r" and then return the
string from that point forward.

Kaiser, this is the shortcut you was looking for, now I would do a hack
there, I would read chunks of the file as reading byte to byte is expensive,
then I would go from the back of the buffer looking for NewLine, if found,
then you have your string, if not store the entire buffer in a StringBuilder
and read another chunk, now you will have to call StringBuilder.Insert
instead of Append.


cheers,
 
Hi,

Of course that if the files are small maybe this is not needed.


cheers,
 
And just to add my 2 cents, if the lines in the file are all the same
length, you can just seek from the end of the file back the length of
the line, then read the line.
 
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
dot.state.fl.us> said:
Kaiser, this is the shortcut you was looking for, now I would do a hack
there, I would read chunks of the file as reading byte to byte is expensive,
then I would go from the back of the buffer looking for NewLine, if found,
then you have your string, if not store the entire buffer in a StringBuilder
and read another chunk, now you will have to call StringBuilder.Insert
instead of Append.

Note also that this requires significant knowledge of the encoding
being used. It's easy if it's a fixed size per character (eg ASCII, or
UCS-2). It's harder if the length varies by character (eg with UTF-8).
 
Jon Skeet said:
<"Ignacio Machin \( .NET/ C# MVP \)" <ignacio.machin AT
Note also that this requires significant knowledge of the encoding
being used. It's easy if it's a fixed size per character (eg ASCII, or
UCS-2). It's harder if the length varies by character (eg with UTF-8).

Yes, and it's especially fun going backwards :) (At least UTF-8 is better
in this respect than older MBCS and other encodings.)
I didn't really think the OP would use this method, as this is anything but
a "shortcut" - but I should have mentioned it anyway.
 
Back
Top