2017-12-04 9 views
2

サーバ上の共有フォルダを監視して、ネットワークに接続されたコンピュータがそのフォルダ内で行う変更を監視する必要がありますホスト名)。私はC#を使ってディレクトリとファイルの監視を実装しました。しかし、Created、Renamed、Changed、Deleted、Errorイベントなどのイベントのみを監視します。 また、共有フォルダへのアクセスや変更を行ったコンピュータのホスト名/ IPアドレスと、イベントが発生した時刻を監視するのに役立つ必要があります。 は、ここに私のコードです:私はこのアプローチを試してみましたサーバ上の共有フォルダの変更を行っているコンピュータのホスト名/ IPアドレスを知る方法

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 
using System.IO; 
using System.Threading; 
namespace a1ashiishFileSystemWatcher 
{ 
    public partial class MainForm : Form 
    { 
     public ListBoxlistBox; 
     public const String startMonitoring = “Start Minitoring…”; 
     public const String stopMonitoring = “Stop Minitoring…”; 
     public MainForm() 
     { 
      InitializeComponent(); 
      //Create a listBox to show activities of all Events. 
      listBox = new ListBox(); 
      listBox.FormattingEnabled = true; 
      listBox.Location = new System.Drawing.Point(23, 121); 
      listBox.Name = “listBox”; 
      listBox.Size = new System.Drawing.Size(571, 238); 
      listBox.TabIndex = 2; 
      this.Controls.Add(listBox); 
     } 
     private voidbutton1_Click(object sender, EventArgs e) 
     { 
      // Create FolderBrowserDialog object. 
      FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog(); 
      // Show a button to create a new folder. 
      folderBrowserDialog.ShowNewFolderButton = true; 
      DialogResult dialogResult = folderBrowserDialog.ShowDialog(); 
      // Get selected path from FolderBrowserDialog control. 
      if (dialogResult == DialogResult.OK) 
      { 
       textBox1.Text = folderBrowserDialog.SelectedPath; 
       Environment.SpecialFolderroot = folderBrowserDialog.RootFolder; 
      } 
     } 
     private voidbutton2_Click(object sender, EventArgs e) 
     { 
      // Create a new FileSystemWatcher object. 
      FileSystemWatcher fsWatcher = new FileSystemWatcher(); 
      switch (button2.Text) 
      { 
       // Start Monitoring… 
       case startMonitoring: 
        if (!textBox1.Text.Equals(String.Empty)) 
        { 
         listBox.Items.Add(“Started FileSystemWatcher Service…”); 
         fsWatcher.Path = textBox1.Text; 
         // Set Filter. 
         fsWatcher.Filter = (textBox2.Text.Equals(String.Empty)) ? “*.*” : textBox2.Text; 
         // Monitor files and subdirectories. 
         fsWatcher.IncludeSubdirectories = true; 
         // Monitor all changes specified in the NotifyFilters. 
         fsWatcher.NotifyFilter = NotifyFilters.Attributes | 
               NotifyFilters.CreationTime | 
               NotifyFilters.DirectoryName | 
               NotifyFilters.FileName | 
               NotifyFilters.LastAccess | 
               NotifyFilters.LastWrite | 
               NotifyFilters.Security | 
               NotifyFilters.Size; 
         fsWatcher.EnableRaisingEvents = true; 
         // Raise Event handlers. 
         fsWatcher.Changed += new FileSystemEventHandler(OnChanged); 
         fsWatcher.Created += new FileSystemEventHandler(OnCreated); 
         fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted); 
         fsWatcher.Renamed += new RenamedEventHandler(OnRenamed); 
         fsWatcher.Error += new ErrorEventHandler(OnError); 
         button2.Text = stopMonitoring; 
         textBox1.Enabled = false; 
         textBox2.Enabled = false; 
        } 
        else 
        { 
         listBox.Items.Add(“Please select folder to monitor….”); 
        } 
        break; 
       // Stop Monitoring… 
       case stopMonitoring: 
       default: 
        fsWatcher.EnableRaisingEvents = false; 
        fsWatcher = null; 
        button2.Text = startMonitoring; 
        textBox1.Enabled = true; 
        textBox2.Enabled = true; 
        listBox.Items.Add(“Stopped FileSystemWatcher Service…”); 
        break; 
      } 
     } 
     // FileSystemWatcher – OnCreated Event Handler 
     public voidOnCreated(object sender, FileSystemEventArgs e) 
     { 
      // Add event details in listbox. 
      this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}” || Action : {1}”, e.FullPath, e.ChangeType)); }); 
     } 
     // FileSystemWatcher – OnChanged Event Handler 
     public voidOnChanged(object sender, FileSystemEventArgs e) 
     { 
      // Add event details in listbox. 
      this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}” || Action : {1}”, e.FullPath, e.ChangeType)); }); 
     } 
     // FileSystemWatcher – OnRenamed Event Handler 
     public voidOnRenamed(object sender, RenamedEventArgs e) 
     { 
      // Add event details in listbox. 
      this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}” || Action : {1} to “{2}””, e.FullPath, e.ChangeType, e.Name)); }); 
     } 
     // FileSystemWatcher – OnDeleted Event Handler 
     public voidOnDeleted(object sender, FileSystemEventArgs e) 
     { 
      // Add event details in listbox. 
      this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Path : “{0}” || Action : {1}”, e.FullPath, e.ChangeType)); }); 
     } 
     // FileSystemWatcher – OnError Event Handler 
     public void OnError(object sender, ErrorEventArgse) 
     { 
      // Add event details in listbox. 
      this.Invoke((MethodInvoker)delegate { listBox.Items.Add(String.Format(“Error : {0}”, e.GetException().Message)); }); 
     } 
    } 
} 

、それでも私は、ホスト名を取得することはできませんよ。私が間違っているところで私を助けてください。私の知る限り

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() 
     { 
     } 
    } 
} 
+3

私は 'FileSystemWatcher'では不可能であるかなり確信していますネットワーク内の別のマシンからではありません。私はあなたがそのフォルダを共有しているマシンにそのコードを置き、関連するWindows APIをチェックすることが可能であればそれをチェックする必要があります。 –

+0

変更が入った場所から実際にマシン/ IPが必要か、実際に* User *を取得するのが面白いでしょうか?私の推測は、後者の方が簡単だと思います。 – Fildor

+0

@Fildorはい、私たちは共有フォルダを変更しているサーバ上のクライアントマシンのホスト名を特定する必要があります – beginner

答えて

0

あなたは、少なくとも共有に接続されているものを取得するためにWMIを使用することができます。 System.Management.dllを参照し、ManagementObjectSearcherというインスタンスを作成してください。

問題は一般的に正しいクラスを見つけることであり、WMIの参照はWMI Referenceの下にあります。あなたの場合、Win32_ConnectionShareクラスが必要です。そのクラスからデータにアクセスするには、アプリケーションが管理者特権で実行する必要があることを考慮してください。

ご利用の場合のために少しのコード例(上記のドキュメントantecedentを述べに従ってdependentは、クライアント側を表しながら、サーバ側を表します):

// Create a query for system environment variables only 
SelectQuery query = new SelectQuery("SELECT * FROM Win32_ConnectionShare"); 

// Initialize an object searcher with this query 
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); 

// Get the resulting collection and loop through it 
foreach (ManagementObject mo in searcher.Get()) 
{ 
    string antecedent = mo["antecedent"].ToString(); 
    string dependent = mo["dependent"].ToString(); 

    ManagementObject share = new ManagementObject(antecedent); 
    ManagementObject server = new ManagementObject(dependent); 

    Console.WriteLine(server["UserName"].ToString()); 
    Console.WriteLine(server["ComputerName"].ToString()); 
    Console.WriteLine(server["ShareName"].ToString()); 
} 
関連する問題