相关疑难解决方法(0)

将多个文件添加到目录时,FileSystemWatcher会出现文件访问错误

当多个文件放入监视目录时,我遇到了FileSystemWatcher的问题.我想在文件放入目录后立即解析它.通常,第一个文件解析正常,但向目录添加第二个文件会导致访问问题.偶尔,第一个文件甚至不会解析.只有一个应用程序正在运行并正在查看此目录.最终,此进程将在多台计算机上运行,​​并且它们将监视共享目录,但只有一台服务器可以解析每个文件,因为数据已导入数据库且没有主键.

这是FileSystemWatcher代码:

public void Run() {
  FileSystemWatcher watcher = new FileSystemWatcher("C:\\temp");
  watcher.NotifyFilter = NotifyFilters.FileName;
  watcher.Filter = "*.txt";

  watcher.Created += new FileSystemEventHandler(OnChanged);

  watcher.EnableRaisingEvents = true;
  System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
}
Run Code Online (Sandbox Code Playgroud)

然后是解析文件的方法:

private void OnChanged(object source, FileSystemEventArgs e) {
  string line = null;

  try {
    using (FileStream fs = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.None)) {
      using (StreamReader sr = new StreamReader(fs)) {
        while (sr.EndOfStream == false) {
          line = sr.ReadLine();
          //parse the line and insert into the database
        }
      }
    }
  }
  catch (IOException ioe) …
Run Code Online (Sandbox Code Playgroud)

c# filesystemwatcher exception-handling file-access

38
推荐指数
2
解决办法
4万
查看次数