I am creating a directory and setting up a FileSystemWatcher on it. Then I create a file. All this is done in the form constructor. In a button event handler I delete the directory created above. Sometimes it throws a IOException: The directory is not empty. After this I cannot even access the child directory in explorer. I keep getting Access is Denied Errors. This directory gets deleted after my process exits. AFAIK FileSystemWatcher should not a lock a directory.
string alphaBeta = @"Alpha\Beta";
public Form1()
{
InitializeComponent();
Directory.CreateDirectory(alphaBeta);
FileSystemWatcher watcher = new FileSystemWatcher()
{
Path = alphaBeta,
Filter = "*.dat",
NotifyFilter = NotifyFilters.FileName
};
watcher.EnableRaisingEvents = true;
File.WriteAllText(alphaBeta + @"\Gamma.dat", "Delta");
}
private void btnDelete_Click(object sender, EventArgs e)
{
Directory.Delete("Alpha", true);//Recursively Delete
}
How do I properly delete the directory without getting the directory stuck?
UPDATE: Above is minimal reproducible example
My actual scenario involves a addin loaded in explorer.exe that monitors a config directory for changes. It hooks into create and rename events of FSW.
The delete code runs in the uninstaller. Uninstaller is not supposed to kill explorer. We thought FileSystemWatcher will not lock the Folder and will silently stop monitoring changes once the directory is deleted. But this doesn't seem to be the case.