更新时读取文件。错误进程无法访问该文件,因为该文件正由另一个进程使用

时间:2018-01-22 18:01:37

标签: c#

我想在更新时阅读CSV文件的最后一行。当我保存更新时,应用程序会出现此错误“进程无法访问文件”,因为正在被其他进程使用。“我的问题是,”另一个进程“是观察者?如果是观察者,我怎样才能在更新时读取文件?

public partial class Auto_Window : Form
    {

        FileSystemWatcher watcher = new FileSystemWatcher();

        private int i = 0;

        public Auto_Window()
        {
            InitializeComponent();

            watcher.Path = ConfigurationManager.AppSettings["CSVFolder"];
            watcher.NotifyFilter = NotifyFilters.LastWrite;
            watcher.Filter = ConfigurationManager.AppSettings["CSVFilter"];
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            watcher.EnableRaisingEvents = true;
        }

        private void OnChanged(object source, FileSystemEventArgs e)
        {
            i++;
            var data = File.ReadAllLines(e.FullPath);
            string last = data[data.Length - 1];

            if (i == 1)
            {
                tb_art1.Invoke(new Action(() => tb_art1.Text = last));
            }
            if (i == 2)
            {
                tb_art2.Invoke(new Action(() => tb_art2.Text = "ART2"));
            }
            if (i == 3)
            {
                tb_art3.Invoke(new Action(() => tb_art3.Text = "ARTO3"));
                MessageBox.Show("com?");
                tb_art1.Invoke(new Action(() => tb_art1.Text = ""));
                tb_art2.Invoke(new Action(() => tb_art2.Text = ""));
                tb_art3.Invoke(new Action(() => tb_art3.Text = ""));
                i = 0;
            }
       }

        private void btn_auto_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btn_conf_Click(object sender, EventArgs e)
        {
            if ((Control.ModifierKeys & Keys.Shift) != 0 && (Control.ModifierKeys & Keys.Control) != 0)
            {
                Config cfgform = new Config();
                cfgform.ShowDialog();
                watcher.Path = ConfigurationManager.AppSettings["CSVFolder"];
                watcher.Filter = ConfigurationManager.AppSettings["CSVFilter"];
            }
        }

        private void btn_clear_Click(object sender, EventArgs e)
        {
            tb_art1.Text = "";
            tb_art2.Text = "";
            tb_art3.Text = "";
            i = 0;
        }
    }

更新:代码已更新

1 个答案:

答案 0 :(得分:0)

我解决了在事件开始时添加 watcher.EnableRaisingEvents = false; 并在最后添加 watcher.EnableRaisingEvents = true; 以防止重复修改的问题。

另一个问题是我阅读文件的方式。我这样解决了:

        var fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        var reader = new StreamReader(fs);

        await Task.Delay(500);

        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            searchList.Add(line);
        }