C# file/folder monitor
I already managed to see file and folder changes with the FileSystemWatcher.
开发者_Go百科My problem is that I can't make a difference between files and folder. It's possible that a file and a folder have the same path names.
For the delete event I even can't use a dirty workarround with testing File.Exists(path) or Directory.Exists(path) because the file/folder is already deleted when the method is called.
Maybe this object has the info I need but I didn't found it:
FileSystemEventArgs e
I only want to know if the changed item was a file or a folder.
Assuming it's on a NTFS volume I think you could do what you need by looking at the Change Journals. Specifically the FSCTL_READ_USN_JOURNAL control code and looking at the FileAttributes of the USN_RECORD to see if it's a FILE_ATTRIBUTE_DIRECTORY
.
You can find a sample here (in C++, but could possibly translate to C# or otherwise maybe just write a small C++ dll to call from your app): Walking a Buffer of Change Journal Records
You could test whether it has the Directory attribute:
var attributes = File.GetAttributes(@"c:\somepath");
if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
// it's a directory
}
else
{
// it's a file
}
Of course if it has already been deleted this won't work and you won't be able to tell the type.
I've found a solution which is clean and always works:
The standard setting of a watcher is for files and folders. This makes no sense in my eyes since I can't find out which type the changed object had.
It's possible to create two filewatchers. One for files and one for folders. Then you just have to change the default settings as follows:
// for file
fileSysWatchFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
// for folder
fileSysWatchDir.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
It is not possible to retrieve the type of the deleted item unless you had a list of path->type mappings before where you can look up the last type of the deleted item.
精彩评论