读取文本文件实时记录过程中的错误

时间:2015-07-08 14:01:30

标签: c# visual-studio logging

我正在使用c#构建一个Windows软件来读取不断变化的日志(文本文件)(每秒)

以下是我的代码。当我运行它时,我得到一个错误

  

mscorlib.dll中出现“System.IO.IOException”类型的异常   但未在用户代码中处理。

     

其他信息:进程无法访问该文件   'C:\ Users \ Steve \ Documents \ Visual Studio   2015 \ Projects \ iosLogger \ IosSysLogger \ bin \ Debug \ syslog.txt'因为它   正在被另一个进程使用。

我的逻辑背后是我想要构建一个记录器,每次对它进行更改时都会读取文本文件。但它似乎只是调用和循环(它无论如何崩溃)我的问题是什么?

 string currentPath = System.Environment.CurrentDirectory;
    public Form1()
    {

        InitializeComponent();

        string currentPath = System.Environment.CurrentDirectory;


        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = currentPath;
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
                               | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        watcher.Filter = "*.*";
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;


    }

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        textBox1.BeginInvoke(new Action(() =>
        {
            string[] fileContents;
            fileContents = File.ReadAllLines(currentPath + @"\syslog.txt");

            foreach (string line in fileContents)
            {
                textBox1.AppendText(line + "\n");
            }
        }));
    }

0 个答案:

没有答案