Code examples of WMI for C # server performance monitoring

Source: Internet
Author: User
Tags dot net

1.WMI Introduction

WMI is a shorthand for the English Windows Management instrumentation, and by using WMI, we can get performance parameters and process runs for local or remote servers, as well as most of the hardware information, provided that the running user has sufficient privileges. such as the Administrator group of users. It is also a convenient and fast way to do load balancing.

2. When using, first add System.Management.dll and then reference

Using System.Management;

3. Define Remote access

public class Managementconnectpool ...        {private static System.Management.ConnectionOptions Conn = new ConnectionOptions ();        private static ManagementObjectSearcher MoS = new ManagementObjectSearcher ();        private string username = "";        private string pwd = "";        private string Space= "";        private string server = ""; Public Managementconnectpool (String mpusername,string mppwd, String mpspace, String mpserver) ...            {this.username = Mpusername;            This.pwd = mppwd;            This.space = Mpspace;            This.server = Mpserver;            Conn.username = Mpusername;            Conn.password = mppwd;            String scopestring = "//" + Mpserver + mpspace;            System.Management.ManagementScope Ms = new Managementscope (scopestring);            Ms.connect (); Mos.        Scope = Ms; } Public managementobjectcollection Getqueryresult (string queryString) ... {ObjectQuery OQ = new ObjectQuery (); Oq.            QueryString = QueryString; Mos.            Query = OQ; Managementobjectcollection MoC =mos.            Get ();        return MOC; }    }

4. Get information about CPU, memory, network traffic, etc.

public class Monitor ...        {private String username = "";        private string pwd = "";        private string IP = "";        Managementconnectpool MCP;                Wmsserverclass server; Public Monitor (String username,string pwd,string IP) ...            {this.username = username;            This.pwd = pwd;            This.ip = IP;            MCP = new Managementconnectpool (username,pwd, "/root/cimv2", IP);        Server = new Wmsserverclass (); The WMI way gets the NIC traffic #region WMI way to get the NIC traffic private void Getnetworkflow () ... {Managementobjectcollection MOC = Mcp.getqueryresult (@ "SELECT * from Win32_NetworkAdapter where macaddress<>null            and manufacturer<> ' Microsoft '); string[] List = new String[moc.            Count]; foreach (System.Management.ManagementObject mymac in MOC) ... {String A = mymac["Speed"].            ToString ();//null WMI does not implement this property Console.WriteLine (A.tostring ()); }        }        #endregion WMI way to get CPU information #region WMI way to get CPU information private void Getcpuinfo () ...            {Managementobjectcollection MOC = Mcp.getqueryresult ("SELECT * from Win32_Processor"); string[] List = new String[moc.            Count];            int i = 0; foreach (ManagementObject mo in MOC) ... {string total = mo. GetPropertyValue ("Loadpercentage").                ToString ();                List[i]=total;            i++; }} #endregion WMI way to get memory usage #region WMI way to get memory usage public string getmemoryusage () ...            {Managementobjectcollection MOC = Mcp.getqueryresult ("SELECT * from Win32_LogicalMemoryConfiguration"); int totalm = 1;            int avilablem = 1; foreach (ManagementObject mo in MOC) ... {string total = mo. GetPropertyValue ("TotalPhysicalMemory").                ToString (); Totalm = Int.            Parse (total); } MOC = Mcp.getqueryreSult ("SELECT * from Win32_PerfRawData_PerfOS_Memory"); foreach (ManagementObject mo in MOC) ... {string avilable = mo. GetPropertyValue ("Availablekbytes").                ToString (); Avilablem = Int.            Parse (avilable);            } int usedm = Totalm-avilablem;            Double memoryusage = (double) usedm * (double) +/(double) Totalm; Return memoryusage.        ToString (); } #endregion}

5. Get Local Machine information (WEB)

1. How to obtain the capacity of the specified disk in WMI #region 1. How to obtain the capacity of a specified disk with WMI private string DriveType (String type) ...             {string Rtntype= ""; Switch (type) ...                     {case ' 1 ': rtntype= ' not Type ';                 Break                     Case "2": rtntype= "floppy disk";                 Break                     Case "3": rtntype= "hard disk";                 Break                     Case ' 4 ': rtntype= "removable drive or network drive";                 Break                     Case "5": rtntype= "CD-ROM";                 Break                     Case "6": rtntype= "RAM disk";                 Break             Default:break;         } return Rtntype; private void Button1_Click (object sender, System.EventArgs e) ... {selectquery query=new selectquery ("SElect * from Win32_LogicalDisk ");              ManagementObjectSearcher searcher=new managementobjectsearcher (query); foreach (Managementbaseobject disk in searcher. Get ()) ... {Response.Write (disk["Name"] + "" +drivetype (disk["DriveType"].              ToString ()) + "" + disk["VolumeName"]+ "<br>"); }} #endregion 2. How to obtain the capacity of a specified disk in WMI #region 2. How to obtain the capacity of a specified disk with WMI private void button2_click (obj ECT sender, System.EventArgs e) ...              {ManagementObject disk = new ManagementObject ("win32_logicaldisk.deviceid=" C: ""); Disk.              Get ();                      Response.Write ("Logical Disk Size =" + disk["size"] + "bytes"); } #endregion 3. How to list all shared resources in a machine #region 3. How to list all shared resources in the machine private void button3_click (object sender, System.EventArgs e) ...              {ManagementObjectSearcher searcher = new ManagementObjectSearcher ("SELECT * from Win32_Share"); Foreach (ManagementObject share in searcher. Get ()) ... {Response.Write (share).              GetText (textformat.mof)); }} #endregion 4. How to write Process control to let a folder in the system share or unshared #region 4. How to write Process control to share or unshared private void in a folder on the system Button4_Click (object sender, System.EventArgs e) ... {/**//* First, this requires a user with the appropriate permissions to log on to the system object[] obj = {"C:/temp", "My Shares", 0,10, "Dot Net implemented sharing              ",""};              Change to object[] obj = {"C:/temp", "My Share", 0,null, "Dot Net implemented Share", ""};             Can be authorized to the most users.              */ManagementClass _class = new ManagementClass (New Managementpath ("Win32_Share")); object[] obj = ...             {"C:/temp", "My Share", 0,10, "Dot Net implemented Share", ""}; _class.          InvokeMethod ("create", obj); } #endregion 5. How to obtain the running state of the system service #region 5. How to obtain the running state of the system service private void Button5_click (object sender, Sy Stem. EventArgs e) ... {string[] Lvdata = new StRING[4];              ManagementObjectSearcher Searcher =new ManagementObjectSearcher ("SELECT * FROM Win32_Service"); foreach (ManagementObject mo in searcher. Get ()) ... {Lvdata[0] = mo["Name"].                  ToString (); LVDATA[1] = mo["StartMode"].                  ToString (); if (mo["Started"].                  Equals (True)) lvdata[2] = "Started";                  else lvdata[2] = "Stop"; LVDATA[3] = mo["StartName"].                  ToString ();                                 Response.Write (Lvdata[0]+lvdata[1]+lvdata[2]+lvdata[3]); }} #endregion 6. Modify the IP through WMI without restarting #region 6. IP modification via WMI, without restarting private V OID Button6_click (object sender, System.EventArgs e) ...              {Reportip ();              Switchtodhcp ();              Switchtoprivate ();              Thread.Sleep (5000);              Reportip (); Response.writE ("end."); } private void Switchtodhcp () ...              {Managementbaseobject inpar = null;              Managementbaseobject outpar = null;              ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration"); Managementobjectcollection MOC = MC.              GetInstances (); foreach (ManagementObject mo in MOC) ... {if (!                   (bool) mo["ipenabled"]) continue; Inpar = mo.                  Getmethodparameters ("EnableDHCP"); Outpar = mo.                  InvokeMethod ("EnableDHCP", inpar, NULL);              Break }} private void Switchtoprivate () ...              {Managementbaseobject inpar = null;              Managementbaseobject outpar = null;              ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration"); Managementobjectcollection MOC = MC.           GetInstances ();   foreach (ManagementObject mo in MOC) ... {if (!                   (bool) mo["ipenabled"]) continue; Inpar = mo.                   Getmethodparameters ("Enableprivate"); inpar["IPAddress"] = new string[] ...                   {"192.168.1.1"}; inpar["SubnetMask"] = new string[] ...                  {"255.255.255.0"}; Outpar = mo.                  InvokeMethod ("Enableprivate", inpar, NULL);              Break }} private void Reportip () ...              {Response.Write ("****** current IP addresses:");              ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration"); Managementobjectcollection MOC = MC.              GetInstances (); foreach (ManagementObject mo in MOC) ... {if (!                   (bool) mo["ipenabled"]) continue;                 String str= "{0} SVC: ' {1} ' MAC: [{2}]"; Str= string. Format (mo["Caption"]. ToString (), mo["ServiceName"]. ToString (), mo["MACAddress"].                  ToString ());                   Response.Write (str);                  String[] addresses = (string[]) mo["IPAddress"];                   String[] subnets = (string[]) mo["IPSubnet"];                  Response.Write ("Addresses:");                   foreach (string sad in Addresses) Response.Write (sad+ "<br>");                  Response.Write ("subnets:");              foreach (string sub in subnets) Response.Write (sub+ "<br>"); }} #endregion 7. How to remotely restart a remote computer using WMI #region 7. How to remotely restart a remote computer using WMI private void Button7_click ( Object sender, System.EventArgs e) ...              {Response.Write ("Computer details retrieved using Windows Management Instrumentation (WMI)");              Response.Write ("mailto:singlepine@hotmail.com"); Response.Write ("=========================================================================");              Connecting a remote computer connectionoptions CO = new connectionoptions (); Co.              Username = "John"; Co.              Password = "John";                    System.Management.ManagementScope ms = new System.Management.ManagementScope ("//192.168.1.2/root/cimv2", CO); Querying the remote computer System.Management.ObjectQuery OQ = new System.Management.ObjectQuery ("SELECT * from Win32_o                                  Peratingsystem ");              ManagementObjectSearcher Query1 = new ManagementObjectSearcher (MS,OQ); Managementobjectcollection QueryCollection1 = Query1.                          Get (); foreach (ManagementObject mo in QueryCollection1) ... {string[] ss= ...                  {""}; Mo.                  InvokeMethod ("Reboot", SS); Response.Write (Mo.              ToString ());  }} #endregion 8. Create a new process with WMI #region 8. Use WMI to create a new process private void Button8_click (object SenDer, System.EventArgs e) ... {//get the object on which the method would be invoked managementclass Processclass = new Managem               Entclass ("Win32_Process"); Get an input parameters object for this method managementbaseobject Inparams = Processclass.getmethodparame               Ters ("Create");               Fill in input parameter values inparams["CommandLine"] = "calc.exe";               Execute the method Managementbaseobject Outparams = Processclass.invokemethod ("Create", inparams, NULL); Display Results//note:the Return code of the method is provided in the "returnvalue" proper Ty of the Outparams object Response.Write ("Creation of Calculator process returned:" + outparams["Returnvalu              E "]);           Response.Write ("Process ID:" + outparams["processId"]); } #endregion 9. How to terminate a process through WMI #region 9. How to terminate a process through WMI private void button9_Click (object sender, System.EventArgs e) ...              {ManagementObject service = new ManagementObject ("win32_service=" WinMgmt "");              Invokemethodoptions options = new Invokemethodoptions (); Options.                Timeout = new TimeSpan (0,0,0,5); Managementbaseobject outparams = service.              InvokeMethod ("StopService", null, Options);         Response.Write ("Return Status =" + outparams["returnvalue"]); } #endregion 10. How to use WMI to get the directory of the remote machine and the file #region 10. How to use WMI to get the directory of the remote machine and the file private void Button10_clic K (object sender, System.EventArgs e) ...              {ManagementObject disk = new ManagementObject ("win32_logicaldisk.deviceid=" C: ""); Disk.              Get ();         Response.Write ("Logical Disk Size =" + disk["size"] + "bytes"); } #endregion 11. The MAC address of the NIC #region 11. The MAC address of the network card private void Button11_click (object sender, System.ev   Entargs e)       ...              {ManagementClass MC = new ManagementClass ("Win32_NetworkAdapterConfiguration"); Managementobjectcollection MOC = MC.              GetInstances (); foreach (ManagementObject mo in MOC) ... {if (bool) mo["ipenabled"] = = True) Response.Write ("MAC address" +mo["MacAddress"].                  ToString () + "<br>"); Mo.              Dispose ();  }} #endregion 12.CPU serial number #region 12.CPU serial number private void Button12_click (object sender, System.EventArgs e) ... {String cpuInfo = "";//cpu serial number ManagementClass cimobject = new ManagementClass ("Win32_Processor")              ; Managementobjectcollection MOC = Cimobject.              GetInstances (); foreach (ManagementObject mo in MOC) ... {cpuInfo = mo. properties["Processorid"].                  Value.tostring ();             Response.Write (CpuInfo); }} #endregiOn 13. Motherboard serial number #region 13. Motherboard serial number private void Button13_click (object sender, System.EventArgs e): .             {ManagementObjectSearcher searcher=new managementobjectsearcher ("SELECT * from Win32_baseboard"); foreach (ManagementObject share in searcher. Get ()) ... {Response.Write ("motherboard manufacturer:" + share["Manufacturer"].                 ToString ()); Response.Write ("Model:" +share["Product").                 ToString ()); Response.Write ("Serial Number:" +share["SerialNumber"].             ToString ()); }} #endregion 14. Get HDD id#region 14. Get the hard drive id private void Button14_click (object sender, Sys Tem. EventArgs e) ...              {String HDid;              ManagementClass cimobject = new ManagementClass ("win32_diskdrive"); Managementobjectcollection MOC = Cimobject.              GetInstances (); foreach (ManagementObject mo in MOC) ... {HDid = (string) mo. properties["Model"].                  Value;               Response.Write (HDid); }} #endregion 15. Get the local user list #region 15. Get the user list for this computer private void Button15_click (object send Er, System.EventArgs e) ...             {selectquery query = new SelectQuery ("SELECT * from Win32_UserAccount");             ManagementObjectSearcher searcher = new ManagementObjectSearcher (query); foreach (ManagementObject os in searcher. Get ()) ...             {Response.Write (os["Name"]); }} #endregion}


With the method described above, it is easy to get the performance, process and hardware information of the remote or local machine. In addition: WMI can also be called by using scripts such as VBScript.

Description: Some of the resources from the Netizen Hill Blog. But it's not enough to elaborate on the server performance capabilities of WMI!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.