如何在不使用循环的情况下跳过在C#中读取文本文件 [英] How to skip reading text file in C# without using looping
问题描述
如何跳过阅读日志/文本文件行。假设今天我的日志文件有1000个行。我已经完全读完了。所以我需要保留该行不作为书签,我也能够获得该行。第二天,我的日志文件发生了变化,并添加了2000个没有行。所以我不想从头开始阅读它需要从1001到2000读取它。所以如何在不使用任何循环的情况下这样做,因为如果我使用循环然后它再次从头到尾阅读。请帮帮我。
How to skip reading log/text files line. Suppose today my log file having 1000 nos of line. I have read it completely already. So i need to keep that line no as bookmarks and i am able to get that line no as well. And next day my log file change and added 2000 no of lines. So i don't want to read it from start i need to read it from 1001 to 2000. So how to do that without using any looping because if i am using looping then its again reading from start to end. Please help me on this.
推荐答案
您可以使用:
You can use this:
var lines = File.ReadLines(ofd.FileName);
foreach (string line in lines.Skip(8))
Trace.WriteLine(line);
Because the File.ReadLines returns an IEnumerable<string>, the lines are only loaded when iterated.
Also check File.ReadLines Method http://msdn.microsoft.com/en-us/library/dd383503.aspx
快乐编码小时; _)
Happy coding Hours ;_)
解决方案1:
在阅读之前重命名日志文件,例如通过在文件名中添加日期,然后阅读它。然后,新条目将记录到新的空日志文件中。这样你就不必跟踪任何东西了。
解决方案2:
阅读日志文件时你可能会使用StreamReader并调用ReadLine()在循环中反复出现?您可以通过StreamReader.BaseStream.Position获取文件中StreamReader的字节位置。我并不是100%确定这与最后一行的读取完全匹配,但如果不匹配则会非常接近。将该位置保存在某个位置 - 在额外的文件或数据库中 - 当您下次打开日志文件时,在开始ReadLine()之前在该位置前寻找BaseStream。
Solution 1:
Rename the log file before you read it, e.g. by adding the date into the filename, and then read it. The new entries then get logged into a new empty log file. That way you won't have to track anything.
Solution 2:
When reading the log file you probably use a StreamReader and call ReadLine() repeatedly in a loop? You can get the byte-position of the StreamReader in the file via StreamReader.BaseStream.Position. I'm not 100% sure that this matches the end of the last line read exactly but if it doesn't it will be "very close". Save that position somewhere - in an extra file or in a database - and when you open the logfile the next time, seek the BaseStream ahead to that position before starting to ReadLine().
这篇关于如何在不使用循环的情况下跳过在C#中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!