C # and WMI usage tips 1th/2 page _c# Tutorial

Source: Internet
Author: User
Tags dot net exception handling microsoft sql server readline
1. What is WMI


WMI is a shorthand for English Windows Management instrumentation, which functions primarily by accessing information and services from local hosts, and managing remote computers (you must have sufficient privileges), such as restarting, shutting down, shutting down processes, creating processes, and so on.


2. How do I get local disk information using WMI?


First you create a project in Vs.net, and then reference a. NET assembly in the Add Reference: System.Management.dll so that your project can use WMI. The code is as follows:


Using System;


Using System.Management;








Class Sample_managementobject


{


public static int Main (string[] args)


{


SelectQuery query=new selectquery ("SELECT * from Win32_LogicalDisk");


ManagementObjectSearcher searcher=new managementobjectsearcher (query);


foreach (Managementbaseobject disk in searcher. Get ())


{


Console.WriteLine ("\ r \ n" +disk["Name"] + "" +disk["DriveType"] + "" + disk["VolumeName"]);


}








Console.ReadLine ();





return 0;





}





}





The return value of the disk["DriveType"] has the following meaning:





1 No Type


2 floppy disk


3 Hard Disk


4 removable drive or network drive


5 CD-ROM


6 RAM Disk








3. How do I get the capacity of a specified disk with WMI?


Using System;


Using System.Management;





This is example demonstrates reading a property of a managementobject.


Class Sample_managementobject


{


public static int Main (string[] args)


{


ManagementObject disk = new ManagementObject (


"Win32_logicaldisk.deviceid=\" C:\ "");


Disk. Get ();


Console.WriteLine ("Logical Disk size =" + disk["size"] + "bytes");


Console.ReadLine ();


return 0;


}


}








4. How to list all the shared resources in the machine?


Using System;


Using System.Management;





Class TestApp {


[STAThread]


static void Main ()


{


ManagementObjectSearcher searcher = new ManagementObjectSearcher (


"SELECT * from Win32_Share");


foreach (ManagementObject share in searcher. Get ())


{


Console.WriteLine (Share. GetText (textformat.mof));


}


}








}


Don't forget to add System.Management in the quote.








5, how to write the control of the system to share or cancel a shared folder.?


First, this requires a user with the appropriate permissions to log on to the system. Then, try the following code:


Using System;


Using System.Management;





Class Createshare


{


public static void Main (string[] args)


{


ManagementClass _class = new ManagementClass (New Managementpath ("Win32_Share"));





object[] obj = {"C:\\Temp", "My Share", 0,10, "Share of Dot Net implementation", ""};





_class. InvokeMethod ("create", obj);


}


}


Will


object[] obj = {"C:\\Temp", "My Share", 0,10, "Share of Dot Net implementation", ""};


To


object[] obj = {"C:\\Temp", "My Share", 0,null, "Share of Dot Net implementation", ""};


You can implement authorization to the maximum number of users.








6. How to get the running state of the system service?


private void GetServices ()


{


Managementobjectcollection querycollection;


string[] Lvdata = new String[4];





Try


{


Querycollection = Getservicecollection ("SELECT * FROM Win32_Service");


foreach (ManagementObject mo in querycollection)


{


Create child node for operating system


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





Create List item


ListViewItem Lvitem = new ListViewItem (lvdata,0);


LISTVIEWSERVICES.ITEMS.ADD (Lvitem);


}


}


catch (Exception e)


{


MessageBox.Show ("Error:" + e);


}


}








7, through WMI to modify the IP, and implementation does not have to reboot?


Using System;


Using System.Management;


Using System.Threading;





Namespace Wmiipchanger


{


Class Ipchanger


{


[Mtathread]


static void Main (string[] args)


{


Reportip ();


Switchtodhcp ();


Switchtostatic ();


Thread.Sleep (5000);


Reportip ();


Console.WriteLine ("End.");


}





static 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


}


}





static void Switchtostatic ()


{


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 ("EnableStatic");


Inpar["IPAddress"] = new string[] {"192.168.1.1"};


inpar["SubnetMask"] = new string[] {"255.255.255.0"};


Outpar = mo. InvokeMethod ("EnableStatic", inpar, NULL);


Break


}


}





static void Reportip ()


{


Console.WriteLine ("Hu Jintao Current IP addresses:");


ManagementClass mc = new ManagementClass ("Win32_NetworkAdapterConfiguration");


Managementobjectcollection MOC = MC. GetInstances ();


foreach (ManagementObject mo in MOC)


{


if (! (bool) mo["ipenabled"])


Continue





Console.WriteLine ("{0}\n SVC: ' {1} ' MAC: [{2}]", (string) mo["Caption"],


(string) mo["ServiceName"], (string) mo["MACAddress");





String[] addresses = (string[]) mo["IPAddress"];


String[] subnets = (string[]) mo["IPSubnet"];





Console.WriteLine ("Addresses:");


foreach (string sad in addresses)


Console.WriteLine ("\ t ' {0} '", sad);





Console.WriteLine ("Subnets:");


foreach (string sub in subnets)


Console.WriteLine ("\ t ' {0} '", sub);


}


}


}


}








8. How do I use WMI to remotely reboot a remote computer?


Using System;


Using System.Management;


Namespace WMI3


{


<summary>


Summary description for Class1.


</summary>


Class Class1


{


static void Main (string[] args)


{


Console.WriteLine ("Computer details retrieved using Windows Management Instrumentation (WMI)");


Console.WriteLine ("Mailto:written%2002/01/02%20by%20john%20o ' Donnell%20-%20csharpconsulting@hotmail.com");


Console.WriteLine ("========================================


=================================");


Connecting to 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 remote computers


System.Management.ObjectQuery OQ = new System.Management.ObjectQuery ("SELECT * from Win32_OperatingSystem");





ManagementObjectSearcher Query1 = new ManagementObjectSearcher (MS,OQ);


Managementobjectcollection QueryCollection1 = Query1. Get ();


foreach (ManagementObject mo in QueryCollection1)


{


String[] ss={""};


Mo. InvokeMethod ("Reboot", SS);


Console.WriteLine (Mo. ToString ());


}


}


}


}








9. Create a new process with WMI?


Using System;


Using System.Management;





This sample demonstrates invoking a WMI method using Parameter objects


public class InvokeMethod


{


public static void Main ()


{





Get the "object on which" the method would be invoked


ManagementClass Processclass = new ManagementClass ("Win32_Process");





Get an input Parameters object


Managementbaseobject inparams = processclass.getmethodparameters ("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 ' provided in the ' ReturnValue ' property of the Outparams object


Console.WriteLine ("Creation of calculator process returned:" + outparams["returnvalue"]);


Console.WriteLine ("Process ID:" + outparams["ProcessID"]);


}


}








10. How do I terminate a process through WMI?


Using System;


Using System.Management;





This example demonstrates how to stop a system service.


Class Sample_invokemethodoptions


{


public static int Main (string[] args) {


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





Console.WriteLine ("Return Status =" + outparams["returnvalue"]);





return 0;


}


}








11. How to use WMI to obtain directories and files for remote machines. Like how to list all the files in a directory, or all subdirectories; How to delete, lick, and change files?


Using System;





Using System.Management;





This is example demonstrates reading a property of a managementobject.





Class Sample_managementobject





{





public static int Main (string[] args) {





ManagementObject disk = new ManagementObject (





"Win32_logicaldisk.deviceid=\" C:\ "");





Disk. Get ();





Console.WriteLine ("Logical Disk size =" + disk["size"] + "bytes");





return 0;





}





}





13. Some skills


I use WMI to remove the MAC address of the NIC. The serial number of the CPU, the serial number of the motherboard, the serial number of the motherboard has been checked, the rest is to be verified, because I am using a notebook, the back of the notebook has a serial number of the motherboard, so you can be sure that the motherboard series number is no problem





MAC address of the NIC





SELECT MACAddress from Win32_NetworkAdapter WHERE ((MACAddress are not NULL) and (manufacturer <> ' Microsoft '))





Result: 08:00:46:63:ff:8c








Serial number of the CPU





Select Processorid from Win32_Processor





Result: 3febf9ff00000f24








Serial number of the motherboard





Select SerialNumber from Win32_BIOS





Results: 28362630-3700521


Get the hard drive ID


String Hdid;


ManagementClass cimobject = new ManagementClass ("win32_diskdrive");


Managementobjectcollection MOC = Cimobject. GetInstances ();


foreach (ManagementObject mo in MOC)


{


Hdid = (string) mo. properties["Model"].value;





MessageBox.Show (Hdid);


}








14. An exception handling problem after using WMI


Here's a piece of code I've sorted out.





Managementobjectcollection QueryCollection1;


ConnectionOptions CO = new connectionoptions ();


Co. Username = "Administrator";


Co. Password = "111";


Try


{


System.Management.ManagementScope ms = new System.Management.ManagementScope (@ "\\csnt3\root\cimv2", CO);


System.Management.ObjectQuery OQ = new System.Management.ObjectQuery ("SELECT * from Win32_OperatingSystem");


ManagementObjectSearcher Query1 = new ManagementObjectSearcher (MS,OQ);





QueryCollection1 = Query1. Get ();


foreach (ManagementObject mo in QueryCollection1)


{


String[] ss={""};


Mo. InvokeMethod ("Reboot", SS);


Console.WriteLine (Mo. ToString ());


}


}


catch (Exception ee)


{





Console.WriteLine ("Error");





}








15. Windows Management Instrumentation (WMI) is a scalable system management architecture that employs a unified, standards-based, extensible object-oriented interface. WMI provides you with a standard way to interact with system management information and the underlying WMI API. WMI is used primarily by system management application developers and administrators to access and operating system management information.


WMI can be used to build tools for organizing and managing system information, allowing administrators or system administrators to monitor system activity more closely. For example, you can use WMI to develop an application to call an administrator when a Web server crashes.


Using WMI with the. NET Framework


WMI provides a number of specifications to achieve almost any administrative task for many high-end applications, such as Microsoft Exchange, Microsoft SQL Server, and Microsoft Internet Information Services (IIS). Administrators can perform the following tasks:


? Monitor the health of your application.


? Detect bottlenecks or failures.


? Manage and configure your application.


? Querying application data (using traversal and query of object relationships).


? Perform a seamless local or remote administration operation.


The WMI structure consists of the following three layers:


? Client


Software components that use WMI to perform actions, such as reading administrative details, configuring systems, and subscribing to events.


? Object Manager


The intermediary device between the provider and the client that provides key services such as standard event publishing and subscriptions, event filtering, query engines, and so on.


? Provider


Software components that capture real-time data and return it to the client application, handle method calls from the client, and link the client to the managed infrastructure.


The ability to provide data and events and configure the system seamlessly to clients and applications through well-defined schemas. In the. NET framework, the System.Management namespace provides a common class for traversing the WMI schema.


In addition to the. NET framework, you need to install WMI on your computer to use the administrative features in that namespace. If you are using Windows Millennium Edition, Windows 2000, or Windows XP, WMI is already installed. Otherwise, you will need to download WMI from MSDN.


Access management information with System.Management


The System.Management namespace is the WMI namespace in the. NET framework. This namespace includes the following first-level class objects that support WMI operations:


? ManagementObject or ManagementClass: a single Management object or class, respectively.


? ManagementObjectSearcher: Used to retrieve a collection of ManagementObject or ManagementClass objects based on a specified query or enumeration.


? ManagementEventWatcher: Used to subscribe event notifications from WMI.


? Managementquery: Serves as the basis for all query classes.


The use encoding paradigm for the System.Management class is appropriate for the. NET framework environment, and WMI uses the standard base framework whenever appropriate. For example, WMI uses the. NET collection classes extensively and uses the recommended encoding pattern, such as the "delegate" mode of. NET asynchronous operations. Therefore, developers using the. NET framework can use their current skills to access administrative information about a computer or application.


Please see


Using WMI to manage applications | Retrieving the collection of Management Objects | Query Management Information | Booking and using Administrative events | How to perform Administrative objects | Remote processing and Connectivity Options | Using strongly typed objects


Current 1/2 page 12 Next read the full text

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.