How to watch NTFS Symbolic links changes with FileSystemWatcher

FileSystemWatcher does not observes changes in symbolic links targets and only way how to do that is to follow them also.

First we set up main FileSystemWatcher:

static void Main(string[] args)
{
    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = Environment.CurrentDirectory + "\\"+"Observed";
    watcher.IncludeSubdirectories = true;
    watcher.Created += new FileSystemEventHandler(watcher_Created);
    watcher.EnableRaisingEvents = true;

    Console.ReadLine();
}

And second part is to watch newly created symbolic links

static void watcher_Created(object sender, FileSystemEventArgs e)
{
    try
    {
        Console.WriteLine("Created: " + e.FullPath);
        FileAttributes attributes = File.GetAttributes(e.FullPath);
// Now, check whether directory is Reparse point or symbolic link
        if (attributes == (FileAttributes.Directory | FileAttributes.ReparsePoint))
        {

            FileSystemWatcher watcher = new FileSystemWatcher();

            string path = JunctionPoint.GetTarget(e.FullPath);
            watcher.Path = path;
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.IncludeSubdirectories = true;
            watcher.EnableRaisingEvents = true;
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex);
    }

}

 

For finding target of Symbolic links is used JunctionPoint library, which basically uses pInvoke from links below. Note, that that library does not works without changes for sybolic links, because it works only with reparse points. Problem with that library is that works only with reparse points and symbolic links uses different structure REPARSE_DATA_BUFFER (an extra field Flags) and also does not identifies correctly symbolic link reparse tag returned from DeviceIoControl function.

In attached sample is corrected version.

Sample here: https://cid-60515fd39eb2a86f.skydrive.live.com/self.aspx/Ve%c5%99ejn%c3%a9/blog%20files/SymLinkTest.zip

Links:

Reparse_Data_Buffer:

http://msdn.microsoft.com/en-us/library/ms791514.aspx

DeviceIoControl Function

http://msdn.microsoft.com/en-us/library/aa363216(VS.85).aspx

JunctionPoint library (changed)

http://www.codeproject.com/KB/files/JunctionPointsNet.aspx

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s