文本文件的阅读最后一行 [英] Read last line of text file

查看:150
本文介绍了文本文件的阅读最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道如何读取文本文件的最后一行。我需要找到行,然后将其加工成SQL数据库...我一直在阅读和周围淘网,但我挣扎着找到合适的方式来做到这一点。即:

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 but am battling to find the proper way to do this. I.e.:


  1. 找到文件的最后一行。

  2. 文件的过程最后一行。

我希望这是有道理的。

推荐答案

有两种方法:简单且效率低下,或窘况复杂,但有效率。这个复杂的版本假设一个健全的编码。

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();

请注意,这里使用的 File.ReadLines ,的的的 File.ReadAllLines 。如果您使用.NET 3.5或更早版本你需要使用 File.ReadAllLines 或者自己写code - ReadAllLines 将读取的全部的文件到内存中一气呵成,而 readlines方法流了。

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.

否则,复杂的方法是使用类似<一个code href=\"http://stackoverflow.com/questions/452902/how-to-read-a-text-file-reversely-with-iterator-in-c-sharp\">this.它试图从文件末尾向后读取,处理污秽如UTF-8多字节字符。这不是令人愉快的。

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.

这篇关于文本文件的阅读最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆