Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from a growing file in C#?

In C#/.NET (on Windows) is there a way to read a "growing" file using a file stream? The length of the file will be very small when the filestream is opened, but the file will be being written to by another thread. If/when the filestream "catches up" to the other thread (i.e. when Read() returns 0 bytes read), I want to pause to allow the file to buffer a bit, then continue reading.

I don't really want to use a FilesystemWatcher and keep creating new file streams (as was suggested for log files), since this isn't a log file (it's a video file being encoded on the fly) and performance is an issue.

Thanks,
Robert

like image 265
Robert Fraser Avatar asked Sep 11 '09 07:09

Robert Fraser


People also ask

Does fread read whole files?

fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count . Use the feof or ferror function to distinguish a read error from an end-of-file condition.

How read a string from a file in C++?

Call open() method to open a file “tpoint. txt” to perform read operation using object newfile. If file is open then Declare a string “tp”. Read all data of file object newfile using getline() method and put it into the string tp.


1 Answers

You can do this, but you need to keep careful track of the file read and write positions using Stream.Seek and with appropriate synchronization between the threads. Typically you would use an EventWaitHandle or subclass thereof to do the synchronization for data, and you would also need to consider synchronization for the access to the FileStream object itself (probably via a lock statement).

Update: In answering this question I implemented something similar - a situation where a file was being downloaded in the background and also being uploaded at the same time. I used memory buffers, and posted a gist which has working code. (It's GPL but that might not matter for you - in any case you can use the principles to do your own thing.)

like image 174
Vinay Sajip Avatar answered Oct 09 '22 18:10

Vinay Sajip