使用 C# 读取大型文本文件的最后一个符号或行的最有效方法是什么?
问问题
3046 次
6 回答
5
假设您的文本文件是 ASCII,此方法将允许您直接跳转到最后一个字符并避免读取文件的其余部分(就像到目前为止给出的所有其他答案一样)。
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
stream.Seek(-1, SeekOrigin.End);
byte b = (byte)stream.ReadByte();
char c = (char)b;
}
如果您的程序需要处理多字节编码,您可能需要执行一些复杂的逻辑,如Skeet 的答案所示。但是,鉴于您的情况仅限于读取最后一个字符,您可以实现特定于您预期编码的简化版本。下面的代码适用于 UTF-8(这是当今最流行的编码)。可能会使您的Seek
阅读器处于前一个字符的中间,但解码器会在它读取最后一个字符时从中恢复。
FileInfo fileInfo = new FileInfo(path);
int maxBytesPerChar = Encoding.UTF8.GetMaxByteCount(1);
int readLength = Math.Min(maxBytesPerChar, (int)fileInfo.Length);
using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
{
reader.DiscardBufferedData();
reader.BaseStream.Seek(-readLength, SeekOrigin.End);
string s = reader.ReadToEnd();
char c = s.Last();
}
于 2013-10-07T08:18:56.170 回答
4
如果文件不是太大,只需阅读这些行并选择最后一个:
string lastLine = File.ReadLines("pathToFile").LastOrDefault(); // if the file is empty
所以你以这种方式得到最后一个字符:
Char lastChar = '\0';
if(lastLine != null) lastChar = lastLine.LastOrDefault();
File.ReadLines
在开始处理之前不需要读取所有行,因此在内存消耗方面很便宜。
这是来自 J. Skeet 的更复杂的方法:如何在 C# 中使用迭代器反向读取文本文件
于 2013-10-07T08:10:49.773 回答
0
string s = File.ReadAllText("test.txt");
string[] split = s.Split(s[s.Length - 1]);
最后一行:-
var lastLine = File.ReadLines("test.txt").Last();
于 2013-10-07T08:11:10.857 回答
0
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line = sr.ReadToEnd();
Console.WriteLine(line[line.length-1);
}
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
于 2013-10-07T08:11:17.337 回答
0
我建议使用 File-Class 的 ReadToEnd-Method,所以你不需要关闭 Steam/TextReader:
string s = File.ReadAllText(@"YOUR PATH HERE");
char lastchar = s[s.Length - 1];
于 2013-10-07T08:14:58.440 回答
-1
于 2013-10-07T08:10:06.447 回答