简体   繁体   English

使用C#监视WMI文件

[英]WMI Files Montioring using C#

I am working on WMI(Windows Management Instrumentation) in C# and stuck at a point. 我正在使用C#开发WMI(Windows管理规范) ,并停留在某个地方。

I have to create an application using WMI (C#) similar to File System Watcher. 我必须使用类似于File System Watcher的 WMI(C#)创建一个应用程序

I would like to get notified every time whenever within a particular folder a new file is created or deleted. 每当在特定文件夹中创建或删除新文件时,我都希望得到通知。

MY WQL query is : 我的WQL查询是:

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

While running the query using wbemtest , it displays an Error message prompting Invalid Class. 使用wbemtest运行查询时,它会显示一条错误消息,提示无效的类。

Can someone please help me out regarding same? 有人可以帮我吗?

In order to detect when a file is created , modified or deleted you must use the __InstanceOperationEvent WMI Class and the using the value of __Class property you can figure out out if the file was modified, deleted o created. 为了检测何时创建,修改或删除文件,您必须使用__InstanceOperationEvent WMI类,并且使用__Class属性的值__Class文件是否被修改,删除或创建。

Try this sample 试试这个样本

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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM