How can I read a text file without locking it?

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

    Explicit set up the sharing mode while reading the text file.

    using (FileStream fs = new FileStream(logFilePath, 
                                          FileMode.Open, 
                                          FileAccess.Read,    
                                          FileShare.ReadWrite))
    {
        using (StreamReader sr = new StreamReader(fs))
        {
            while (sr.Peek() >= 0) // reading the old data
            {
               AddLineToGrid(sr.ReadLine());
               index++;
            }
        }
    }
    

提交回复
热议问题