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
You can do this, but you need to keep careful track of the file read and write positions using
Stream.Seekand with appropriate synchronization between the threads. Typically you would use anEventWaitHandleor subclass thereof to do the synchronization for data, and you would also need to consider synchronization for the access to theFileStreamobject itself (probably via alockstatement).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.)