How can I read a text file without locking it?

后端 未结 7 560
梦谈多话
梦谈多话 2020-11-27 02:42

I have a windows service writes its log in a text file in a simple format.

Now, I\'m going to create a small application to read the service\'s log and shows both th

7条回答
  •  时光取名叫无心
    2020-11-27 03:32

    You need to make sure that both the service and the reader open the log file non-exclusively. Try this:

    For the service - the writer in your example - use a FileStream instance created as follows:

    var outStream = new FileStream(logfileName, FileMode.Open, 
                                   FileAccess.Write, FileShare.ReadWrite);
    

    For the reader use the same but change the file access:

    var inStream = new FileStream(logfileName, FileMode.Open, 
                                  FileAccess.Read, FileShare.ReadWrite);
    

    Also, since FileStream implements IDisposable make sure that in both cases you consider using a using statement, for example for the writer:

    using(var outStream = ...)
    {
       // using outStream here
       ...
    }
    

    Good luck!

提交回复
热议问题