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

2023-11-23

我有一个 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();
            }
        }

我的代码读写有问题吗?

如何解决问题?


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

对于服务 - 您的示例中的作者 - 使用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
   ...
}

祝你好运!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐