Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have to monitor a shared folder on the server for changes taking place in that folder by a computer connected in the network(it's hostname). I implemented monitoring of directory and files using C#. But, it only monitors events like Created, Renamed, Changed, Deleted and Error events. I also need help with monitoring the hostname/IP address of the computer accessing or doing changes to the shared folder. I have tried this approach, but still I am not able to get the hostname. Please help me where I am going wrong! Here is my code :

What I have tried:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace MonitorShare
{
    public partial class Monitor : ServiceBase
    {
        public Monitor()
        {
            InitializeComponent();
            string dDirectory = @"E:\SharedFolder\Shares";
            DirectoryInfo info = new DirectoryInfo(dDirectory);
            string[] filePath = Directory.GetFiles(dDirectory, "*.*");

            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.BeginInit();
            watcher.filePath = dDirectory;
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
            watcher.Changed += new FileSystemEventHandler(watcher_Changed);
            watcher.Created += new FileSystemEventHandler(watcher_Created);
            watcher.Deleted += new FileSystemEventHandler(watcher_Deleted);
            watcher.Filter = "*.*";
            watcher.EnableRaisingEvents = true;
            watcher.EndInit();
        }

        protected void watcher_Deleted(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"", "");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l => l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);
                        
                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" + time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
                process.Close();
            }
        }

        protected void watcher_Created(object sender, FileSystemEventArgs e)
        {
            var process = new Process();
            process.StartInfo.FileName = "openfiles.exe";
            process.StartInfo.Arguments = "/query /FO CSV /v";
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            try
            {
                process.Start();
                if ((process.StandardOutput != null))
                {
                    var result = process.StandardOutput.ReadToEnd().Trim().Replace("\"", "");
                    var lines = result.Split('\n');

                    var firstLineIndex = 1 + lines.Cast<string>().ToList().FindIndex(l => l.Contains("Hostname"));
                    for (var i = firstLineIndex; i < lines.Count() && firstLineIndex > 0; i++)
                    {
                        var fields = lines[i].Split(',');
                        var time = DateTime.Now;
                        FileStream fs = new FileStream(@"C:\SFD\log.txt", FileMode.Append);
                        StreamWriter sw = new StreamWriter(fs);
                        
                        if(firstLineIndex.ToString()=="Hostname")
                        {
                             Console.SetOut(sw);
                             Console.WriteLine(e.FullPath + "\t" + e.ChangeType + "\t" + time + "\t" + e.Name + "\t" + fields[0]);
                             sw.Close();
                        }
                    }
                }
                process.WaitForExit();
            }
            catch (Exception ex)
            {
               
            }
            finally
            {
                process.Close();
            }
         
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }
    }
}
Posted
Updated 12-Dec-17 17:34pm

1 solution

What you want can't be done using a FileSystemWatcher. All it does it tell you "something changed". It has no facility to determine who made the changes not which machine they came from.

Frankly, I don't know if there is any way to determine which machine the changes are coming from. You may be limited to just finding out who made them. Code runs as the user account that launched it, not as the machine it's running on. Though, I don't know how you're going to get the information.
 
Share this answer
 
Comments
raushanaj5 12-Dec-17 23:38pm    
@Dave Did you mean to say that it is difficult to find out the hostname if using another approach also?
Dave Kreskowiak 13-Dec-17 8:06am    
Yep. Windows tracks everything by user account, not the machine anything came from.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900