Redirect writes to a file to a stream C#

2019-02-15 14:09发布

I wanted to ask if it is possible to redirect writes to a specific file, to a memory stream in my application so I can immediately read it. If it is possible please explain how to do so.

Thanks.

3条回答
三岁会撩人
2楼-- · 2019-02-15 14:43

What you need is a stream which writes to a file as well as to another stream which you are watching - a stream splitter, commonly known in the Unix world as tee.

For .NET you can use this implementation of a stream splitter. Pass it a FileStream (so that the file gets written to) and for the second stream, pass a Stream implementation which does whatever you want when the stream is written to (for example, a subclass of MemoryStream with an overridden Write method).

Update: I see from your comment that my answer isn't what you need - I didn't realise from your original question that you had no control over the app writing to file.

In order to get this kind of control, for finest control you will need to go to a low-level driver which intercepts system calls - much like FileMon does. For slightly less control, you can use System.IO.FileSystemWatcher.

查看更多
唯我独甜
3楼-- · 2019-02-15 14:44

I don't know how to do this in the way you say but you could use a FileWatcher to hook file. If its written to you'll be notified and you can read it.

查看更多
可以哭但决不认输i
4楼-- · 2019-02-15 14:59

Make sure your application works with Stream, and then you can use the MemoryStream concrete implementation to accomplish streaming without a file.

查看更多
登录 后发表回答