使用C#读取大型文本文件中最后一个符号或行的最有效方法是什么?
using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
stream.Seek(-1, SeekOrigin.End);
byte b = (byte)stream.ReadByte();
char c = (char)b;
}
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();
}
string lastLine = File.ReadLines("pathToFile").LastOrDefault(); // if the file is empty
Char lastChar = '\0';
if(lastLine != null) lastChar = lastLine.LastOrDefault();
< p >< code >File.ReadLines无需在开始处理之前读取所有行,因此在内存消耗方面非常便宜。
string s = File.ReadAllText("test.txt");
string[] split = s.Split(s[s.Length - 1]);
而对于最后一行:-
var lastLine = File.ReadLines("test.txt").Last();
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);
}
}
}
string s = File.ReadAllText(@"YOUR PATH HERE");
char lastchar = s[s.Length - 1];