Search code examples
c#directoryfilesystemwatcherauditshared-directory

Convert Network share path to a physical folder path


I have a console application that is using a FileSystemWatcher to watch a folder, which fires off an event when there is a file/folder deleted.

My Simplified Code:

using System;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;

namespace FileWatcherConsole
{
    class Program 
    {
        static void Main(string[] args)
        {
            Program program = new Program();
            FileSystemWatcher watcher = new FileSystemWatcher
            {
                Path = "\\Server1",
                IncludeSubdirectories = true,
                EnableRaisingEvents = true,
                NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter = "*.*"
            };
            watcher.Deleted += new FileSystemEventHandler(program.OnDeleted);
            new AutoResetEvent(false).WaitOne();
        }

        private void OnDeleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine(e.FullPath);
        }
    }
}

The application works as expected, except for when watching a network shared folder where the output is

\\Server1\SharedFolder

However I would instead like the physical path of the folder:

C:\Users\myUser\Desktop\SharedFolder

So is there a way to programmatically convert the network path to a physical path ?

I know one solution is to use the physical path when instantiating FileSystemWatcher, however this is not ideal as physical location of the network share folder can change.

P.S. If you deem necessary the reasoning behind this, I need the physical path as I am comparing the the event path [e.FullPath] with system auditing events


Solution

  • Using the ManagementObjectSearcher in the System.Management namespace you can query the remote server for the Win32_Share definition of the share in WMI and build the corresponding local path.

    The article Get local path from UNC path has sample code detailing how to do this.