C#filesystem watcher - 查找触发事件的用户

时间:2017-03-10 23:08:52

标签: c# filesystemwatcher

我构建了一个监视共享网络文件夹(NAS)的Windows服务。在创建,重命名,删除任何文件夹时,我能够将日志写入事件查看器。我的最终目标是找到“由谁创建或重命名或删除”并将其用户名或LanID包含在事件查看器日志中。

我只是在寻找如何处理后续步骤的线索。以下是我现在的代码。

    public partial class NasFolderMonitor : ServiceBase
{
    public const string MyServiceName = "NASFolderWatcher";
    private System.Diagnostics.EventLog eventLog;

    public NasFolderMonitor()
    {
        InitializeComponent();

        eventLog = new System.Diagnostics.EventLog();
        eventLog.Source = "NasMonitorLog";
        eventLog.Log = "NasMonitorLog";
    }

    public void NASFolderWatcher()
    {
        if (!EventLog.SourceExists("NasMonitorLog"))
        {
            EventLog.CreateEventSource("NASFolderWatcher", "NasMonitorLog");
        }

        // Create a new FileSystemWatcher with the path
        FileSystemWatcher NasWatcher = new FileSystemWatcher("Share Path here");
        NasWatcher.IncludeSubdirectories = true;
        NasWatcher.Changed += new FileSystemEventHandler(OnChanged);
        NasWatcher.Created += new FileSystemEventHandler(OnChanged);
        NasWatcher.Deleted += new FileSystemEventHandler(OnChanged);
        NasWatcher.Renamed += new RenamedEventHandler(OnChanged);

        // Begin watching
        NasWatcher.EnableRaisingEvents = true;
    }

    protected override void OnStart(string[] args)
    {
        NASFolderWatcher();
        eventLog.WriteEntry("Monitoring Started");
    }

    protected override void OnStop()
    {
        eventLog.WriteEntry("Monitoring Stopped");
    }

    public void OnChanged(object source, FileSystemEventArgs e)
    {
        WatcherChangeTypes wct = e.ChangeType; 
        eventLog.WriteEntry(e.ChangeType.ToString() + "-" + e.FullPath);
    }
}

1 个答案:

答案 0 :(得分:0)

不确定这是否能完全解决您的问题,但您可能能够获得文件/文件夹等的所有者(因此是创建者?)。我没有运行NAS,但尝试下面的代码,它适用于本地机器:

var fi = new System.IO.FileInfo(@"c:\temp\client_id.json");
var ac = fi.GetAccessControl();
var user=ac.GetOwner(typeof(System.Security.Principal.NTAccount));

Console.WriteLine(user.Value);