Ram*_*Ram -1 c# string io streamreader text-files
我有一个文本文件,我正在使用StreamReader读取。现在根据我的要求,无论我先读了哪几行,我都不想再读一次,这意味着我不想再次获取该数据。所以我添加了File.ReadLines(FileToCopy).Count();代码来获取首先读取的行。现在,以上代码行返回的任何行,我都想在那之后读取。这是我的代码。
string FileToCopy = "E:\\vikas\\call.txt";
if (System.IO.File.Exists(FileToCopy) == true)
{
lineCount = File.ReadLines(FileToCopy).Count();
using (StreamReader reader = new StreamReader(FileToCopy))
{
}
}
Run Code Online (Sandbox Code Playgroud)
我需要在这里指定什么条件。请帮助我。
while ((line = reader.ReadLine()) != null)
{
var nextLines = File.ReadLines(FileToCopy).Skip(lineCount);
if (line != "")
{
}
Run Code Online (Sandbox Code Playgroud)
有一种更快的方法可以执行此操作,该方法不需要您读取整个文件即可到达停止位置。关键是要跟踪文件的长度。然后,您将文件打开为FileStream,定位到上一个长度(即您之前阅读的位置的末尾),然后创建一个StreamReader。所以看起来像这样:
long previousLength = 0;
Run Code Online (Sandbox Code Playgroud)
然后,当您要复制新内容时:
using (var fs = File.OpenRead(FileToCopy))
{
// position to just beyond where you read before
fs.Position = previousLength;
// and update the length for next time
previousLength = fs.Length;
// now open a StreamReader and read
using (var sr = new StreamReader(fs))
{
while (!sr.EndOfStream)
{
var line = sr.ReadLine();
// do something with the line
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将节省您巨大的,如果文件变大量的时间。例如,如果上次读取文件的大小为千兆字节,那么File.ReadLines(filename).Skip(count)将需要20秒才能到达结尾,因此您可以读取下一行。我上面描述的方法将花费更少的时间-可能不到一秒钟。