文件正在被另一个进程使用 [英] File is being used by another process

查看:69
本文介绍了文件正在被另一个进程使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大致可以做到这一点的程序:

I have a program that roughly does this:

  1. 打开文件以进行读取.
  2. 关闭文件
  3. 启动文件监视程序以监视文件中的更改.
  4. 一旦检测到更改,文件监视程序的EnableRaisingEvents标志将设置为false,并且该过程将从步骤1开始重复.

问题是,从第4步转到第1步后,它无法读取文件说明该文件正在被另一个进程使用.

The problem is, after going from step 4 to step 1, it cannot read the file saying that it is being used by another Process.

我收到的错误:

未处理的异常:System.IO.IOException:该进程无法访问文件'c:\ test.xml',因为它正在被另一个进程使用.

Unhandled Exception: System.IO.IOException: The process cannot access the file 'c:\test.xml' because it is being used by another process.

出了什么问题?我程序的步骤1的读取器是否仍打开文件,或者访问文件的过程完全不同,或者尽管将标志设置为false,但文件监视程序在从4移至步骤1后仍在监视文件?

Whats going wrong? does the reader from Step 1 of my program still have the file open, or is some entirely different process accessing the file, or is it that filewatcher is still watching the file after moving to Step 1 from 4, despite setting the flag to false?

推荐答案

如果您的代码与此类似:

If your code is similar to this:

[STAThread]
static void Main(string[] args)
{
    string file = "temp.txt";
    ReadFile(file);
    FileSystemWatcher fswatcher = new FileSystemWatcher(".\\");
    fswatcher.Changed += delegate(object sender, FileSystemEventArgs e)
                             {
                                 ReadFile(e.FullPath);
                             };
    while (true)
    {
        fswatcher.WaitForChanged(WatcherChangeTypes.Changed);
    }
}
private static void ReadFile(string file)
{
    Stream stream = File.OpenRead(file);
    StreamReader streamReader = new StreamReader(stream);
    string str = streamReader.ReadToEnd();
    MessageBox.Show(str);
    streamReader.Close();
    stream.Close();
}

如果要通过记事本编辑文件,则单击保存"按钮时,它将使文件保持打开状态,而好像只是关闭程序并单击保存"则不会.我不知道这是记事本的错误还是未记录的功能,但这可能是您的问题.解决此问题的一种方法是执行以下操作:

If you are editing the file via notepad, then, when you click the save button, it keeps the file open, while as if when you just close the program and click save it doesn't. I do no know if this is a bug or an undocumented feature of notepad, but this just might be your problem. One way to fix this is to do the following:

在您的匿名委托中,或者在执行 ReadFile()的任何地方调用 Thread.Sleep(1000),以使程序在读取文件之前等待并您的代码应该可以正常工作.

In your anonymous delegate, or wherever you execute the call to ReadFile() call Thread.Sleep(1000), to have the program wait before reading the file and your code should work fine.

这篇关于文件正在被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆