C # file / folder monitor

I have already managed to see file and folder changes using FileSystemWatcher.

My problem is that I cannot distinguish between files and folder. It is possible that the file and folder have the same path names.

For a delete event, I can't even use the dirty workarround with testing File.Exists (path) or Directory.Exists (path), because the file / folder is already deleted when the method is called.

Perhaps this object has information that I need, but I did not find it:

FileSystemEventArgs e

I just want to know if the changed item was a file or folder.

+3
source share
4 answers

I found a solution that is clean and always works:

- . , , .

. . :

// for file
fileSysWatchFile.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
// for folder
fileSysWatchDir.NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.LastWrite;
+1

, NTFS, , , , . , FSCTL_READ_USN_JOURNAL FileAttributes USN_RECORD, , FILE_ATTRIBUTE_DIRECTORY.

( ++, # , , DLL ++ ):

+2

You can check if it has an attribute directory :

var attributes = File.GetAttributes(@"c:\somepath");
if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
    // it a directory
}
else
{
    // it a file
}

Of course, if it has already been deleted, this will not work, and you cannot specify the type.

+1
source

It is not possible to get the type of a deleted item if you did not have a list of mappings of type path-> before you can find the last type of deleted item.

0
source

Source: https://habr.com/ru/post/1776014/


All Articles