Read last line of text file

后端 未结 6 1509
耶瑟儿~
耶瑟儿~ 2020-11-28 14:26

I need to know how to read the last line of a text file. I need to find the line and then process it into a SQL database... I\'ve been reading around and scouring the web

6条回答
  •  迷失自我
    2020-11-28 14:32

    There are two ways: simple and inefficient, or horrendously complicated but efficient. The complicated version assumes a sane encoding.

    Unless your file is so big that you really can't afford to read it all, I'd just use:

    var lastLine = File.ReadLines("file.txt").Last();
    

    Note that this uses File.ReadLines, not File.ReadAllLines. If you're using .NET 3.5 or earlier you'd need to use File.ReadAllLines or write your own code - ReadAllLines will read the whole file into memory in one go, whereas ReadLines streams it.

    Otherwise, the complicated way is to use code similar to this. It tries to read backwards from the end of the file, handling nastiness such as UTF-8 multi-byte characters. It's not pleasant.

提交回复
热议问题