Is there a way to determine with the FSW if a file or a directory has been deleted?
I temporary use the "Path" function initially, but later in case of not delete I fix it by Directory.Exists. However that doesn't fix the Delete case
bool isDirectory = Path.GetExtension(e.FullPath) == string.Empty;
if (e.ChangeType != WatcherChangeTypes.Deleted)
{
isDirectory = Directory.Exists(e.FullPath);
}
You could interrogate the FileSystemEventArgs.FullPath
property to tell if it is a directory or a file.
if (Path.GetFileName(e.FullPath) == String.Empty)
{
//it's a directory.
}
To check if it is a file or directory.
Your question only makes sense if there could be a file and a directory with the same name at the same path. e.g. If you have filenames without extension or directories with extension.
If your directories and files follow the usual conventions, just checking for the presence of an extension in the full path(bool iSDirectory = Path.GetExtension(e.FullPath).Equals("");
), which works whether the file/directory exists or not, because the method just parses the path given and has no connection to the file whatsoever.
If you have to deal with the non-conventional issues I mentioned in the beginning, you could check whether a directory or a file exists at that location. If neither does, you treat them as if both were deleted. If one of them does exist, you treat the other as if it was deleted.
Your inquiry implies that you keep a list of the files and directories somewhere, so, checking against that list, you can make your decision about handling.
I think that this approach is better than the solution given that uses two filesystem watchers in order to tell the difference.
Here's a simplified and corrected version of fletcher's solution:
namespace Watcher
{
class Program
{
private const string Directory = @"C:\Temp";
private static FileSystemWatcher _fileWatcher;
private static FileSystemWatcher _dirWatcher;
static void Main(string[] args)
{
_fileWatcher = new FileSystemWatcher(Directory);
_fileWatcher.IncludeSubdirectories = true;
_fileWatcher.NotifyFilter = NotifyFilters.FileName;
_fileWatcher.EnableRaisingEvents = true;
_fileWatcher.Deleted += WatcherActivity;
_dirWatcher = new FileSystemWatcher(Directory);
_dirWatcher.IncludeSubdirectories = true;
_dirWatcher.NotifyFilter = NotifyFilters.DirectoryName;
_dirWatcher.EnableRaisingEvents = true;
_dirWatcher.Deleted += WatcherActivity;
Console.ReadLine();
}
static void WatcherActivity(object sender, FileSystemEventArgs e)
{
if(sender == _dirWatcher)
{
Console.WriteLine("Directory:{0}",e.FullPath);
}
else
{
Console.WriteLine("File:{0}",e.FullPath);
}
}
}
}