Library tutorials & articles
Using WMI From Managed Code
- Introduction
- Working with WMI in .NET
- Modifying Objects & Running Methods
Modifying Objects & Running Methods
Modifying an existing object
Let’s say we need to change the share status of our printer. In order to do that we need to find it in the repository, which we can do using a straightforward SQL query. For example, the following finds a printer with the name ‘Agfa’:
"SELECT * FROM Win32_Printer WHERE DeviceID = 'Agfa'
To initialise the search we create a FindPrinters method. This returns a ManagementObjectSearcher:
private ManagementObjectSearcher
FindPrinters( string printerName)
{
SelectQuery selectQuery = new SelectQuery();
//specify query
selectQuery.QueryString = String.Format(
"SELECT * FROM Win32_Printer
WHERE DeviceID = '{0}'
OR ShareName = '{1}'",
printerName, printerName);
//create new object searcher
ManagementObjectSearcher managementObjectSearcher =
new ManagementObjectSearcher(
this.managementScope, selectQuery);
return managementObjectSearcher;
}
The ManagementObjectSearcher contains all the objects which satisfy the query. We can then use its Get method to find the appropriate printerObject, modify its properties and put it back into the repository:
//check if anything found if (managementObjectSearcher.Get().Count == 0) {
Console.WriteLine(String.Format(
"No printers with the name '{0}'
or shared name '{1}' found.",
printerName, printerName)); } else {
//if found: go through all found objects set sharing
foreach (ManagementObject printerObject in
managementObjectSearcher.Get())
{
// set sharing parameters
if (sharePrinter)
{
printerObject["Shared"] = true;
printerObject["ShareName"] = printerName;
}
else
{
printerObject["Shared"] = false;
printerObject["ShareName"] = "";
}
//put object back in "update only mode"
PutOptions options = new PutOptions();
options.Type = PutType.UpdateOnly;
printerObject.Put(options);
}
}
Note that we use the options type ‘UpdateOnly’ which means ‘update an existing object only without creating a new one’.
Run a method
Let’s try renaming a printer using the RenamePrinter method of the Win32_Printer class. First we need to find an object on which to run the method, which we’ve already covered, and then we call the method. We start by specifying the method parameters, and then execute the method using InvokeMethod:
//specify method parameters
object[] methodParameters = { newPrinterName };
foreach (ManagementObject printerObject in
managementObjectSearcher.Get())
{
...
//call method with specified parameters
object methodResult =
printerObject.InvokeMethod("RenamePrinter",
methodParameters);
//check invokation results
Int32 numericResult = Convert.ToInt32(methodResult);
if (numericResult != 0)
{
switch (numericResult)
{
case 5:
Console.WriteLine("Error: printer access denied");
break;
case 1801:
Console.WriteLine("Error: invalid printer name");
break;
default:
Console.WriteLine("Unknown error");
break ;
}
}
...
}
Note how we check the result: if 0 then the method was invoked successfully, otherwise we display the appropriate error message.
Deleting objects from repository
Again we start with an object search, and this time simply delete it with the Delete() method:
// if found: go through all found objects and delete them
foreach (ManagementObject printerObject in
managementObjectSearcher.Get())
{
printerObject.Delete();
}
So working with WMI from C#, or indeed Visual Basic .NET, is pretty straightforward, and such simplicity should make WMI very popular. It can be used, for example, in automated software testing, or when you need to know if an application has detected a new device, or to check if an application has modified a particular registry key.
Related articles
Related discussion
-
Binary Studio | software development outsourcing Ukraine
by shane124 (4 replies)
-
Chart insertation in a windows form...
by pdhanik (1 replies)
-
Point of Sale Developers: Hardware & C# SDK
by ManiGovindan (7 replies)
-
help with the remote frame buffer protocol from real VNC
by poison (0 replies)
-
Need help making a complete program editable, C# or .net I think
by davelee (1 replies)
Related podcasts
-
A Practical Look at Silverlight 2 Part 1
Now that Silverlight 2 is at the Olympics and making a big splash, we wanted to explore this fascinating technology more. Microsoft Silverlight 2 is a cross-browser, cross-platform, and cross-device plug-in for delivering the next generation of .NET based media experiences and rich interactive ap...
Events coming up
-
Dec
9
GL.net Group Meeting - December 2009
Gloucester, United Kingdom
The beginning of this year holiday season will belong to mocks. Ronnie and Stephen will take us for a tour around exciting world of unit testing.
Comments
Leave a comment
Sign in or Join us (it's free).