FileSystemWatcher locks folder

十年热恋 提交于 2019-12-07 05:54:16

问题


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.



来源:https://stackoverflow.com/questions/28224595/filesystemwatcher-locks-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!