Monday, October 25, 2010

Example of querying an object from WMI in C#

using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Net;
using System.Net.NetworkInformation;
// These next 2 lines can only be used if you have included a Project --> Reference to System.Management
using System.Management;
using System.Management.Instrumentation;

namespace Test1 {
class Program {
static void Main(string[] args) {
Console.Write("Please enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello {0}", name);
Console.ReadLine();

// Set up the connection to the host
ConnectionOptions oConn = new ConnectionOptions();
//oConn.Username = "";
//oConn.Password = "";
System.Management.ManagementScope oMs = new System.Management.ManagementScope("\\\\WIN-V31ZRUWURFW\\root\\cimv2", oConn);

// Set the query to run
System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("SELECT * FROM Win32_Desktop");

ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);

// Get results
ManagementObjectCollection oReturnCollection = oSearcher.Get();

foreach (ManagementObject oReturn in oReturnCollection)
{
if ( oReturn["Name"].ToString() == "WIN-V31ZRUWURFW\\Administrator" )
{
Console.WriteLine("Name: {0}", oReturn["Name"].ToString());
Console.WriteLine("ScreenSaver: {0}", oReturn["ScreenSaverExecutable"].ToString());
try {
Console.WriteLine("Wallpaper: {0}", oReturn["Wallpaper"].ToString());
} catch (NullReferenceException e) {
Console.WriteLine("Wallpaper: None installed");
}
}
}
Console.Read();
}
}
}

No comments:

Post a Comment