本文整理汇总了C#中System.Management.ManagementObjectSearcher类的典型用法代码示例。如果您正苦于以下问题:C# ManagementObjectSearcher类的具体用法?C# ManagementObjectSearcher怎么用?C# ManagementObjectSearcher使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManagementObjectSearcher类属于System.Management命名空间,在下文中一共展示了ManagementObjectSearcher类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetOperatingSystemInfo
protected virtual void GetOperatingSystemInfo(string Name, string UserName, string Password)
{
if (string.IsNullOrEmpty(Name))
throw new ArgumentNullException("Name");
ManagementScope Scope = null;
if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
{
ConnectionOptions Options = new ConnectionOptions();
Options.Username = UserName;
Options.Password = Password;
Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2", Options);
}
else
{
Scope = new ManagementScope("\\\\" + Name + "\\root\\cimv2");
}
Scope.Connect();
ObjectQuery Query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query))
{
using (ManagementObjectCollection Collection = Searcher.Get())
{
foreach (ManagementObject TempNetworkAdapter in Collection)
{
if (TempNetworkAdapter.Properties["LastBootUpTime"].Value != null)
{
LastBootUpTime = ManagementDateTimeConverter.ToDateTime(TempNetworkAdapter.Properties["LastBootUpTime"].Value.ToString());
}
}
}
}
}
示例2: CheckPrinterStatus
/// <summary>
/// List the installed printer drivers and status in Windows.
/// </summary>
public static void CheckPrinterStatus()
{
ManagementObjectSearcher query;
ManagementObjectCollection queryCollection;
string sQuery = "SELECT * FROM Win32_Printer";
string sDefault = string.Empty;
try
{
query = new ManagementObjectSearcher(sQuery);
queryCollection = query.Get();
//Loop thru the returned collection of printers
foreach( ManagementObject mo in queryCollection )
{
sDefault = string.Empty;
if ((bool)mo["Default"])
sDefault = "[DEFAULT]";
MessageBox.Show("DeviceID: " + (string)mo["DeviceID"] + "\n" +
"DriverName: " + Convert.ToString(mo["DriverName"]) + "\n" +
"PrinterStatus: " + Convert.ToString(mo["PrinterStatus"]) + "\n" +
"PrinterState: " + Convert.ToString(mo["PrinterState"]),
"Printer Driver " + sDefault,
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
catch (Exception ex)
{
throw ex;
}
}
示例3: PlatformHelper
/// <summary>
/// Initializes the <see cref="PlatformHelper"/> class.
/// </summary>
static PlatformHelper()
{
Win32NT = Environment.OSVersion.Platform == PlatformID.Win32NT;
XpOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 5;
VistaOrHigher = Win32NT && Environment.OSVersion.Version.Major >= 6;
SevenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 1));
EightOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 2, 9200));
EightPointOneOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(6, 3));
TenOrHigher = Win32NT && (Environment.OSVersion.Version >= new Version(10, 0));
RunningOnMono = Type.GetType("Mono.Runtime") != null;
Name = "Unknown OS";
using (
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem"))
{
foreach (ManagementObject os in searcher.Get())
{
Name = os["Caption"].ToString();
break;
}
}
Name = Regex.Replace(Name, "^.*(?=Windows)", "").TrimEnd().TrimStart(); // Remove everything before first match "Windows" and trim end & start
Is64Bit = Environment.Is64BitOperatingSystem;
FullName = string.Format("{0} {1} Bit", Name, Is64Bit ? 64 : 32);
}
示例4: GetProcessUserName
public string GetProcessUserName(int pid)
{
string text1 = null;
SelectQuery query = new SelectQuery("Select * from Win32_Process WHERE processID=" + pid);
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
try
{
foreach (ManagementObject disk in searcher.Get())
{
ManagementBaseObject inPar = null;
ManagementBaseObject outPar = null;
inPar = disk.GetMethodParameters("GetOwner");
outPar = disk.InvokeMethod("GetOwner", inPar, null);
text1 = outPar["User"].ToString();
break;
}
}
catch
{
text1 = "SYSTEM";
}
return text1;
}
示例5: DoCheck
public virtual object DoCheck()
{
var processStats = ProcessStats();
var results = new ArrayList();
using (var query = new ManagementObjectSearcher("SELECT * FROM Win32_Process"))
{
foreach (ManagementObject process in query.Get())
{
try
{
var processId = (uint)process.GetPropertyValue("ProcessId");
var imageName = (string)process.GetPropertyValue("Name");
// Ignore System Idle Process for now
if (imageName.ToString().ToLower() == "system idle process")
{
continue;
}
var fullUserName = string.Empty;
var outParameters = process.InvokeMethod("GetOwner", null, null);
if (outParameters["User"] != null)
{
fullUserName = string.Format(@"{0}\{1}", outParameters["Domain"], outParameters["User"]);
}
var stats = processStats[processId];
var cpuPercentage = stats[0];
ulong workingSet = stats[1];
decimal memoryPercentage = Decimal.Round(((decimal)workingSet / (decimal)_totalMemory * 100), 2);
results.Add(new object[] { processId, imageName, fullUserName, cpuPercentage, memoryPercentage, workingSet });
// flag check
if (Agent.Flags.ContainsKey("ProcessCheck"))
{
if (imageName == Agent.Flags["ProcessCheck"])
{
bool perf = PerformanceCounterBasedProcessCheck.IsProcessRunning(imageName);
if (!perf)
{
Log.Error("Process Check: '" + Agent.Flags["ProcessCheck"] + "' process does not show in Perf Counters.");
}
}
}
}
catch (ManagementException ex)
{
// Process could have ended before reaching this point in the loop
if (ex.Message.ToLower() == "not found")
{
continue;
}
}
}
return results;
}
}
示例6: ObjectQuery
public static List<EntDisk>GetDiskDetails(ManagementScope scope)
{
_logger.Info("Collecting disk details for machine " + scope.Path.Server);
ObjectQuery query = null;
ManagementObjectSearcher searcher = null;
ManagementObjectCollection objects = null;
List<EntDisk> lstDisk = new List<EntDisk>();
try
{
query = new ObjectQuery("Select * from Win32_DiskDrive");
searcher = new ManagementObjectSearcher(scope, query);
objects = searcher.Get();
lstDisk.Capacity = objects.Count;
foreach (ManagementBaseObject obj in objects)
{
lstDisk.Add(FillDetails(obj));
obj.Dispose();
}
}
catch (Exception e)
{
_logger.Error("Exception is disk collection " + e.Message);
}
finally
{
searcher.Dispose();
}
return lstDisk;
}
示例7: find_arduino
private void find_arduino()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_SerialPort");
foreach (ManagementObject queryObj in searcher.Get())
{
string deviceName = queryObj["Name"].ToString();
if (deviceName.Contains("Arduino"))
{
_arduinoPort.PortName = queryObj["DeviceID"].ToString();
_comPortSelection.Text = queryObj["DeviceID"].ToString();
return;
}
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
示例8: GenerateComputerID
internal static string GenerateComputerID()
{
//Creates the HWID from the ProcessorID, Video Controller RAM and the size of the disk drive ; you can change this of course
StringBuilder computerID = new StringBuilder();
ManagementObjectSearcher searcher;
searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor");
foreach (ManagementObject queryObj in searcher.Get())
{
computerID.Append(queryObj["ProcessorId"]);
}
searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_VideoController");
foreach (ManagementObject queryObj in searcher.Get())
{
computerID.Append(queryObj["AdapterRAM"]);
}
searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_DiskDrive");
foreach (ManagementObject queryObj in searcher.Get())
{
computerID.Append(queryObj["Size"]);
}
return computerID.ToString();
}
示例9: GetPhisicalMemory
/// <summary>
/// 获取系统内存大小
/// </summary>
/// <returns> 内存大小(单位M) </returns>
private static int GetPhisicalMemory()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher(); //用于查询一些如系统信息的管理对象
searcher.Query = new SelectQuery("Win32_PhysicalMemory ", "", new[] {"Capacity"}); //设置查询条件
ManagementObjectCollection collection = searcher.Get(); //获取内存容量
ManagementObjectCollection.ManagementObjectEnumerator em = collection.GetEnumerator();
long capacity = 0;
while (em.MoveNext())
{
ManagementBaseObject baseObj = em.Current;
if (baseObj.Properties["Capacity"].Value != null)
{
try
{
capacity += long.Parse(baseObj.Properties["Capacity"].Value.ToString());
}
catch
{
return 0;
}
}
}
return (int) (capacity/1024/1024);
}
示例10: getUserName
public static string getUserName()
{
try
{
var x = "";
var connectionOptions = new ConnectionOptions();
var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions);
var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
using (var searcher = new ManagementObjectSearcher(scope, query))
{
var builder = new System.Text.StringBuilder();
builder.Append(x);
foreach (var row in searcher.Get())
{
builder.Append((row["UserName"].ToString() + " "));
}
x = builder.ToString();
return x;
}
}
catch (Exception ex)
{
return "";
}
}
示例11: Do
public static void Do(string strToFindInCommandLine, string strToFindInCommandLine2, IList<string> filename, bool giveFocus = true)
{
int procID = 0;
string wmiQuery = "select ProcessId, CommandLine from Win32_Process";
ManagementObjectSearcher search = new ManagementObjectSearcher(wmiQuery);
ManagementObjectCollection processList = search.Get();
foreach (ManagementObject process in processList) {
if (process["CommandLine"] != null) {
var cmdLine = process["CommandLine"].ToString();
if (cmdLine.Contains(strToFindInCommandLine) && cmdLine.Contains(strToFindInCommandLine2)) {
procID = Convert.ToInt32(process["ProcessId"]);
}
}
}
if (procID != 0) {
IntPtr winHandle = FindWindow.GetProcessWindow(procID);
MmdDrop.DropFile(winHandle, filename.Select(x => new MmdDropFile(x)).ToList());
if (giveFocus)
SetForegroundWindow(winHandle);
}
}
示例12: GetComPorts
/// <summary>
/// Gets COM port list.
/// </summary>
/// <returns>Enumerable list of COM ports.</returns>
public static IEnumerable<ComPortItem> GetComPorts()
{
var result = new List<ComPortItem>();
ManagementScope connectionScope = new ManagementScope();
SelectQuery serialQuery = new SelectQuery("SELECT * FROM Win32_SerialPort");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(connectionScope, serialQuery);
try
{
foreach (ManagementObject item in searcher.Get())
{
string portName = item["DeviceID"].ToString();
string portDescription = item["DeviceID"].ToString();
// COM port with Arduino is not detected.
// portDescription.Contains("Arduino") is not working.
// I should find out how to get value "Arduino Uno" from "Описание устройства, предоставленное шиной" parameter.
// And where is this parameter?
result.Add(new ComPortItem(portName, portDescription.Contains("Arduino")));
}
}
catch (ManagementException)
{
}
return result;
}
示例13: GetBatteryPercent
private string GetBatteryPercent()
{
try
{
var scope = new ManagementScope();
SelectQuery query = new SelectQuery("Select EstimatedChargeRemaining From Win32_Battery");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
{
using (ManagementObjectCollection objectCollection = searcher.Get())
{
foreach (ManagementObject mObj in objectCollection)
//this nugget has a lot of info see here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa394074%28v=vs.85%29.aspx
{
PropertyData pData = mObj.Properties["EstimatedChargeRemaining"];
var val = pData.Value;
if ((ushort) val > (ushort) 100)
{
return "100";
}
else
{
return val.ToString().Replace("%",""); //strip % in case it duplicates
}
}
}
}
return "Unk";
}
catch (Exception e)
{
Debug.WriteLine(e);
return "Unk";
}
}
示例14: IterateDevices
private void IterateDevices()
{
Console.WriteLine("Iterating");
string model;
string deviceString;
ManagementObjectSearcher physicalSearch = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive WHERE InterfaceType = \"USB\" AND Size <= 17179869184");
foreach (ManagementObject physicalDrive in physicalSearch.Get())
{
if (physicalDrive["MediaType"].ToString().Substring(0, 9) != "Removable")
continue;
if (physicalDrive["Model"] == null)
model = "Unknown Device";
else
model = physicalDrive["Model"].ToString();
deviceString = model + " - (" + Math.Round(((double)Convert.ToDouble(physicalDrive["Size"]) / 1048576), 2) + " MB)";
ImageDevice newDevice = new ImageDevice(deviceString);
newDevice.size = (long) Convert.ToInt64(physicalDrive["Size"]);
newDevice.name = physicalDrive["Name"].ToString();
newDevice.partitions = Convert.ToInt32(physicalDrive["Partitions"]);
// Now see if there are any mounted volumes
foreach(ManagementObject partition in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskDrive.DeviceID='" + physicalDrive["DeviceID"] + "'} WHERE AssocClass = Win32_DiskDriveToDiskPartition").Get())
foreach(ManagementObject disk in new ManagementObjectSearcher("ASSOCIATORS OF {Win32_DiskPartition.DeviceID='" + partition["DeviceID"] + "'} WHERE AssocClass = Win32_LogicalDiskToPartition").Get())
newDevice.volume = "\\\\.\\" + disk["Name"].ToString();
deviceCombo.Items.Add(newDevice);
}
}
示例15: Win32_SharesSearcher
private static void Win32_SharesSearcher()
{
SelectQuery query = new SelectQuery("select * from Win32_Share where Name=\"" + sharename + "\"");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
foreach (ManagementObject mo in searcher.Get())
{
foreach (PropertyData prop in mo.Properties)
{
form.textBox1.AppendText(prop.Name + " = " + mo[prop.Name] + Environment.NewLine); }
//form.textBox1.AppendText(string.Format("Win32ShareName: {0} Description {1} Path {2} ", mo.Properties["Name"].Value, mo.Properties["Description"].Value, mo.Properties["Path"].Value) + Environment.NewLine);
}
}
ManagementObject winShareP = new ManagementObject("root\\CIMV2", "Win32_Share.Name=\"" + sharename + "\"", null);
ManagementBaseObject outParams = winShareP.InvokeMethod("GetAccessMask", null, null);
form.textBox1.AppendText(String.Format("access Mask = {0:x}", outParams["ReturnValue"]) + Environment.NewLine);
ManagementBaseObject inParams = winShareP.GetMethodParameters("SetShareInfo");
form.textBox1.AppendText("SetShareInfor in parameters" + Environment.NewLine);
foreach (PropertyData prop in inParams.Properties)
{
form.textBox1.AppendText(String.Format("PROP = {0}, TYPE = {1} ", prop.Name, prop.Type.ToString()) + Environment.NewLine);
}
Object access = inParams.GetPropertyValue("Access");
//Stopped development here because ShareAFolder project exists. The rest of the development is there
//Maybe should copy Sahare a Folder content to here at some point
}