How can I read a text file without locking it?

后端 未结 7 604
梦谈多话
梦谈多话 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:17

    The problem is when you are writing to the log you are exclusively locking the file down so your StreamReader won't be allowed to open it at all.

    You need to try open the file in readonly mode.

    using (FileStream fs = new FileStream("myLogFile.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
    {
        using (StreamReader sr = new StreamReader(fs))
        {
            while (!fs.EndOfStream)
            {
                string line = fs.ReadLine();
                // Your code here
            }
        }
    }
    

提交回复
热议问题