使用c#的WMI文件监控

本文关键字:文件 监控 WMI 使用 | 更新日期: 2023-09-27 18:12:43

我正在用 c# 开发WMI(Windows Management Instrumentation),但是卡住了。

我必须使用WMI (c#)创建一个应用程序,类似于文件系统监视器。

我希望每次在特定文件夹中创建或删除新文件时都能收到通知。

MY WQL查询是:

SELECT * from _InstanceModificationEvent within 2 where TargetInstance ISA 'CIM_DataFile' and TargetInstance.Drive = 'C:' AND TargetInstance.Path='''Test'

当使用wbemtest运行查询时,它显示一条错误消息,提示Invalid Class.

有人能帮我解决这个问题吗?

使用c#的WMI文件监控

为了检测文件何时被创建、修改或删除,必须使用__InstanceOperationEvent WMI类,并且使用__Class属性的值可以确定文件是否被修改、删除或创建。

试试这个示例

using System;
using System.Collections.Generic;
using System.Management;
using System.Text;

namespace GetWMI_Info
{
    public class EventWatcherAsync
    {
        private void WmiEventHandler(object sender, EventArrivedEventArgs e)
        {
            // e.NewEvent
            string wclass = ((ManagementBaseObject)e.NewEvent).SystemProperties["__Class"].Value.ToString();
            string wop = string.Empty;
            switch (wclass)
            {
                case "__InstanceModificationEvent":
                    wop = "Modified";
                    break;
                case "__InstanceCreationEvent":
                    wop = "Created";
                    break;
                case "__InstanceDeletionEvent":
                    wop = "Deleted";
                    break;
            }
            string wfilename = ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["FileName"].ToString();
            if (!string.IsNullOrEmpty(((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Extension"].ToString()))
            {
                wfilename += "." + ((ManagementBaseObject)e.NewEvent.Properties["TargetInstance"].Value)["Extension"].ToString();
            }
            Console.WriteLine(String.Format("The File {0} was {1}", wfilename, wop));

        }
        public EventWatcherAsync()
        {
            try
            {
                string ComputerName = "localhost";
                string WmiQuery;
                ManagementEventWatcher Watcher;
                ManagementScope Scope;

                if (!ComputerName.Equals("localhost", StringComparison.OrdinalIgnoreCase))
                {
                    ConnectionOptions Conn = new ConnectionOptions();
                    Conn.Username = "";
                    Conn.Password = "";
                    Conn.Authority = "ntlmdomain:DOMAIN";
                    Scope = new ManagementScope(String.Format("''''{0}''root''CIMV2", ComputerName), Conn);
                }
                else
                    Scope = new ManagementScope(String.Format("''''{0}''root''CIMV2", ComputerName), null);
                Scope.Connect();
                //Check for changes in the path C:'Test
                WmiQuery = @"Select * From __InstanceOperationEvent Within 1 
                Where TargetInstance ISA 'CIM_DataFile' and TargetInstance.Drive = 'C:' AND TargetInstance.Path='''Test'''";
                Watcher = new ManagementEventWatcher(Scope, new EventQuery(WmiQuery));
                Watcher.EventArrived += new EventArrivedEventHandler(this.WmiEventHandler);
                Watcher.Start();
                Console.Read();
                Watcher.Stop();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0} Trace {1}", e.Message, e.StackTrace);
            }
        }
        public static void Main(string[] args)
        {
            Console.WriteLine("Listening {0}", "__InstanceOperationEvent");
            Console.WriteLine("Press Enter to exit");
            EventWatcherAsync eventWatcher = new EventWatcherAsync();
            Console.Read();
        }
    }
}