File is being used by another process

后端 未结 7 1289
野的像风
野的像风 2021-01-11 21:08

I have a program that roughly does this:

  1. open a file to read from it.
  2. close the file
  3. Start a filewatcher to watch for changes in the file.
7条回答
  •  轮回少年
    2021-01-11 21:38

    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:

    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.

提交回复
热议问题