小编典典

如何在不锁定文本的情况下读取文本文件?

c#

我有一个Windows服务将其日志以简单格式写入文本文件。

现在,我将创建一个小型应用程序以读取服务的日志,并将现有日志和添加的日志显示为实时视图。

问题在于该服务锁定了用于添加新行的文本文件,同时查看器应用程序锁定了该文件以进行读取。

服务代码:

void WriteInLog(string logFilePath, data)
{
    File.AppendAllText(logFilePath, 
                       string.Format("{0} : {1}\r\n", DateTime.Now, data));
}

查看者代码:

int index = 0;
private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                using (StreamReader sr = new StreamReader(logFilePath))
                {
                    while (sr.Peek() >= 0)  // reading the old data
                    {
                        AddLineToGrid(sr.ReadLine());
                        index++;
                    }
                    sr.Close();
                }

                timer1.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


private void timer1_Tick(object sender, EventArgs e)
        {
            using (StreamReader sr = new StreamReader(logFilePath))
            {
                // skipping the old data, it has read in the Form1_Load event handler
                for (int i = 0; i < index ; i++) 
                    sr.ReadLine();

                while (sr.Peek() >= 0) // reading the live data if exists
                {
                    string str = sr.ReadLine();
                    if (str != null)
                    {
                        AddLineToGrid(str);
                        index++;
                    }
                }
                sr.Close();
            }
        }

我的代码在读写方式上有什么问题吗?

如何解决问题?


阅读 367

收藏
2020-05-19

共1个答案

小编典典

您需要确保服务和阅读器都以非独占方式打开日志文件。尝试这个:

对于服务(您的示例中的作家),请使用FileStream如下创建的实例:

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

对于读者,请使用相同的文件,但更改文件访问权限:

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

同样,由于FileStream实现器IDisposable确保在两种情况下都考虑使用using语句,例如对于编写器:

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

祝好运!

2020-05-19