FileSystemWatcher Changed event is raised twice

前端 未结 30 3714
死守一世寂寞
死守一世寂寞 2020-11-22 06:01

I have an application where I am looking for a text file and if there are any changes made to the file I am using the OnChanged eventhandler to handle the event

30条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 06:13

    You could try to open it for write, and if successful then you could assume the other application is done with the file.

    private void OnChanged(object source, FileSystemEventArgs e)
    {
        try
        {
            using (var fs = File.OpenWrite(e.FullPath))
            {
            }
            //do your stuff
        }
        catch (Exception)
        {
            //no write access, other app not done
        }
    }
    

    Just opening it for write appears not to raise the changed event. So it should be safe.

提交回复
热议问题