-1

what I need to accomplish: I need to read a text file that gets updated every 10 sec and dump the new data into. I need to find the best way to do this. I've tried streamreader and file.readalllines, I can get the contents of the txt file, but I don't know how to compare and dump the added lines. Any input would be appreciated, thank you.

  • "and dump new data into" ... into what? Also, how certain are you the file is append-only? Are there any times when this is reset? – Joel Coehoorn Sep 05 '18 at 20:36
  • The said file is read-only and is never wiped or reset, just gets bigger. I'm dumping the array into a textbox using items.add . All I need now is to check for new lines in the txt file and dump only those into the textbox. Thank you for your reply and time. – Patrick Mallory Sep 05 '18 at 20:46
  • If the file new lines are just appended, I suggest you use the [FileStream.Seek()](https://docs.microsoft.com/en-us/dotnet/api/system.io.filestream.seek?redirectedfrom=MSDN&view=netframework-4.7.2#System_IO_FileStream_Seek_System_Int64_System_IO_SeekOrigin_) method to set the reading position. The first time it would be 0. After that, it's the last number of bytes read. When the Timer ticks, verify if the file length has grown and, when positive, `.Seek()` the last position, `.Lock()` the file section you need to read (last read position + number of new bytes) and get just the new bytes added. – Jimi Sep 05 '18 at 23:46

1 Answers1

0

Under the assumptions that this is a log file you're reading, where the data is being appended to end, and you're reading the file every 10 seconds, why don't you keep track of the number of lines read or the last line number from the last read?

You can then check to see whether the current read has exceeded the previous line number or number of lines read. If it has exceeded, you should be able to work out what the new lines were added because you know where you read until previously. You can read from the (previous read line + 1) until the end of file.

Francis
  • 1,798
  • 1
  • 26
  • 32
  • 1
    Lines is weak, because you have to read the entire contents to know where line breaks are (and the file is continually getting bigger, so this will continually get slower). If you can track bytes (not characters!), you can jump to the exact position in the file for the next read op. – Joel Coehoorn Sep 05 '18 at 21:08
  • Ok that kind of works.I have tried counting lines with .length , I can get a value either int or true/false: what would be the syntax to peek/seek a location and start a stream at said location? – Patrick Mallory Sep 05 '18 at 22:58
  • There's a VB.NET solution here : https://stackoverflow.com/questions/15708368/how-to-read-a-specific-line-from-a-text-file-in-vb but I think the C# version using LINQ here is more succinct and easier to understand, so perhaps try using LINQ. https://stackoverflow.com/questions/1262965/how-do-i-read-a-specified-line-in-a-text-file – Francis Sep 05 '18 at 23:12