FileSystemWatcher locks folder

2020-07-11 07:07发布

问题:

I have a FileSystemWatcher listening on a folder. When I try renaming this folder (in Windows Explorer) I get a

The action can't be completed because the folder or a file in it is open in another program

error.

Commenting out the FileSystemWatcher calls fixes this.

I've tried reproducing the error with a simple program, but haven't been successful so I'm not sure what's going on here. Has anyone encountered anything like this with a FileSystemWatcher? If so - what might be causing it?

More information:

The following seems to be enough to cause the error:

FileSystemWatcher fsw = new FileSystemWatcher(path);
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.EnableRaisingEvents = true;

I can rename files in that folder. And sibling files. I even tried putting a return; as the first line in fsw_Deleted. Still didn't work. As didn't closing Visual Studio, and deleting obj and bin, and running again. And I even tried running the exe file not within VS. Still - no lock if it's not running, Locked if it is.

回答1:

I've discovered what caused this. There was a second FileSystemWatcher - on a sub directory of the first - which didn't allow renaming the first.

(I'm still surprised, though. A FileSystemWatcher should be "invisible".)



回答2:

Its going to do that, since your process is looking for files in that folder. What you may want to do is add a handler for fsw.Rename. Then inside that process you should do a RemoveHandler on looking for new files, and then add it back in with the new name of the folder.