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
-
Problem after strong naming an assembly
by rinkurathor1 (0 replies)
-
VB.net class to connect to sql database
by senol01 (2 replies)
-
ASP.NET Patterns every developer should know
by konikula (3 replies)
-
String was not recognized as a valid DateTime.
by buvanasubi (22 replies)
-
help me to get simple requirement
by Slicksim (1 replies)
Related podcasts
-
Looking into the C# Crystal Ball with Charlie Calvert and Bill Wagner
One of the most exciting announcements from PDC was the news about C# 4.0 and Visual Studio 2010. With all the excitement and discussion throughout the event about these new developer tools, we reached out to two experts in the fields. Charlie Calvert and Bill Wagner sat down with Keith and Woody...
Events coming up
-
Dec
6
Developing AJAX Web Applications with Castle Monorail
London, United Kingdom
Monorail is the model-view-controller engine of the Castle Project, bringing many of the best ideas of Ruby on Rails to the .NET world. In this talk, David De Florinier and Gojko Adzic show how Monorail makes it easy to develop .NET based AJAX applications, and how to use the Castle Project to build Web 2.0 applications effectively. Come to this session if you are a .NET web developer. Everyone is welcome!
Comments
Leave a comment
Sign in or Join us (it's free).