本文整理汇总了C#中System.Management.ManagementClass类的典型用法代码示例。如果您正苦于以下问题:C# ManagementClass类的具体用法?C# ManagementClass怎么用?C# ManagementClass使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ManagementClass类属于System.Management命名空间,在下文中一共展示了ManagementClass类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Run
//private char NULL_VALUE = char(0);
public static ProcessReturnCode Run(string machineName, string commandLine, string args, string currentDirectory)
{
var connOptions = new ConnectionOptions
{
EnablePrivileges = true
};
var scope = new ManagementScope(@"\\{0}\root\cimv2".FormatWith(machineName), connOptions);
scope.Connect();
var managementPath = new ManagementPath(CLASSNAME);
using (var processClass = new ManagementClass(scope, managementPath, new ObjectGetOptions()))
{
var inParams = processClass.GetMethodParameters("Create");
commandLine = System.IO.Path.Combine(currentDirectory, commandLine);
inParams["CommandLine"] = "{0} {1}".FormatWith(commandLine, args);
var outParams = processClass.InvokeMethod("Create", inParams, null);
var rtn = Convert.ToUInt32(outParams["returnValue"]);
var pid = Convert.ToUInt32(outParams["processId"]);
if (pid != 0)
{
WaitForPidToDie(machineName, pid);
}
return (ProcessReturnCode)rtn;
}
}
示例2: ViewModel
public ViewModel()
{
mgt = new ManagementClass("Win32_Processor");
procs = mgt.GetInstances();
CPU = new ObservableCollection<Model>();
timer = new DispatcherTimer();
random = new Random();
time = DateTime.Now;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
ProcessorID = GetProcessorID();
processes = Process.GetProcesses();
Processes = processes.Length;
MaximumSpeed = GetMaxClockSpeed();
LogicalProcessors = GetNumberOfLogicalProcessors();
Cores = GetNumberOfCores();
L2Cache = GetL2CacheSize();
L3Cache = GetL3CacheSize();
foreach (ManagementObject item in procs)
L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB";
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += timer_Tick;
timer.Start();
for (int i = 0; i < 60; i++)
{
CPU.Add(new Model(time, 0,0));
time = time.AddSeconds(1);
}
}
示例3: Shutdown
public static void Shutdown(string mode)
{
if (mode == "WMI")
{
ManagementBaseObject mboShutdown = null;
ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
mcWin32.Get();
// Get Security Privilages
mcWin32.Scope.Options.EnablePrivileges = true;
ManagementBaseObject mboShutdownParams = mcWin32.GetMethodParameters("Win32Shutdown");
//Option Flags
mboShutdownParams["Flags"] = "1";
mboShutdownParams["Reserved"] = "0";
foreach (ManagementObject manObj in mcWin32.GetInstances())
{
mboShutdown = manObj.InvokeMethod("Win32Shutdown", mboShutdownParams, null);
}
}
else if (mode == "Core")
{
Process.Start("shutdown", "/s /t 0");
}
}
示例4: CreateShare
/// <summary>
/// Create a share for a given local path, and sets read/write access rights to everybody
/// </summary>
/// <param name="sharePath">local path of directory to be shared</param>
/// <param name="shareName">Share Name</param>
public static bool CreateShare(string sharePath, string shareName)
{
ManagementObject trustee = new ManagementClass("Win32_Trustee").CreateInstance();
trustee["Domain"] = null;
trustee["Name"] = "Everyone";
trustee["SID"] = new Object[] { 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0 }; // everybody
ManagementObject ace = new ManagementClass("Win32_Ace").CreateInstance();
ace["AccessMask"] = 2032127; // full access
ace["AceFlags"] = 0x1 | 0x2; //OBJECT_INHERIT_ACE | CONTAINER_INHERIT_ACE
ace["AceType"] = 0; //Access Allowed
ace["Trustee"] = trustee;
ManagementObject dacl = new ManagementClass("Win32_SecurityDescriptor").CreateInstance();
dacl["DACL"] = new Object[] { ace };
ManagementClass share = new ManagementClass("Win32_Share");
ManagementBaseObject inParams = share.GetMethodParameters("Create");
ManagementBaseObject outParams;
inParams["Description"] = "Create Share Folder";
inParams["Name"] = shareName;
inParams["Path"] = sharePath;
inParams["Type"] = 0x0; // Disk Drive
inParams["Access"] = dacl;
outParams = share.InvokeMethod("Create", inParams, null);
// Check to see if the method invocation was successful
if ((uint)(outParams.Properties["ReturnValue"].Value) != 0)
{
//throw new Exception("Unable to share directory.");
return false;
}
return true;
}
示例5: GetIdentifier
public static string GetIdentifier(string wmiClass, string wmiProperty, string wmiMustBeTrue)
{
if (_log.IsTraceEnabled)
{
_log.Trace(m => m(string.Format("wmiClass:{0}, wmiProperty:{1}, wmiMustBeTrue:{2}", wmiClass, wmiProperty, wmiMustBeTrue)));
}
string result = "";
var managementClass = new ManagementClass(wmiClass);
var moc = managementClass.GetInstances();
foreach (ManagementObject mo in moc)
{
if (mo[wmiMustBeTrue].ToString() == "True")
{
//Only get the first one
if (result == "")
{
try
{
result = mo[wmiProperty].ToString();
break;
}
catch(Exception ex)
{
_log.Warn(ex);
}
}
}
}
return result;
}
示例6: Create
/// <summary>
/// Create a Send Handler.
/// </summary>
/// <param name="adapterName">The Adapter name.</param>
/// <param name="hostName">The Host name.</param>
/// <param name="isDefault">Indicating if the Handler is the default.</param>
public static void Create(string adapterName, string hostName, bool isDefault)
{
PutOptions options = new PutOptions();
options.Type = PutType.CreateOnly;
using (ManagementClass handlerManagementClass = new ManagementClass("root\\MicrosoftBizTalkServer", "MSBTS_SendHandler2", null))
{
foreach (ManagementObject handler in handlerManagementClass.GetInstances())
{
if ((string)handler["AdapterName"] == adapterName && (string)handler["HostName"] == hostName)
{
handler.Delete();
}
}
ManagementObject handlerInstance = handlerManagementClass.CreateInstance();
if (handlerInstance == null)
{
throw new CoreException("Could not create Management Object.");
}
handlerInstance["AdapterName"] = adapterName;
handlerInstance["HostName"] = hostName;
handlerInstance["IsDefault"] = isDefault;
handlerInstance.Put(options);
}
}
示例7: LoadDeviceList
private void LoadDeviceList()
{
devices.Clear();
devices.Add(new SoundDevice("Default", "0000", "0000"));
ManagementPath path = new ManagementPath();
ManagementClass devs = null;
path.Server = ".";
path.NamespacePath = @"root\CIMV2";
path.RelativePath = @"Win32_SoundDevice";
using (devs = new ManagementClass(new ManagementScope(path), path, new ObjectGetOptions(null, new TimeSpan(0, 0, 0, 2), true)))
{
ManagementObjectCollection moc = devs.GetInstances();
foreach (ManagementObject mo in moc)
{
PropertyDataCollection devsProperties = mo.Properties;
string devid = devsProperties["DeviceID"].Value.ToString();
if (devid.Contains("PID_"))
{
string vid = devid.Substring(devid.IndexOf("VID_") + 4, 4);
string pid = devid.Substring(devid.IndexOf("PID_") + 4, 4);
devices.Add(new SoundDevice(devsProperties["Caption"].Value.ToString(), vid, pid));
}
}
}
}
示例8: GetDiskVolumeSerialNumber
//获取硬盘卷标号
public static string GetDiskVolumeSerialNumber()
{
ManagementClass mc = new ManagementClass("win32_NetworkAdapterConfiguration");
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
return disk.GetPropertyValue("VolumeSerialNumber").ToString();
}
示例9: getComPorts
public static string[] getComPorts()
{
var list = new ArrayList();
ManagementClass win32_pnpentity = new ManagementClass("Win32_PnPEntity");
ManagementObjectCollection col = win32_pnpentity.GetInstances();
Regex reg = new Regex(".+\\((?<port>COM\\d+)\\)");
foreach (ManagementObject obj in col)
{
// name : "USB Serial Port(COM??)"
string name = (string)obj.GetPropertyValue("name");
if (name != null && name.Contains("(COM"))
{
// "USB Serial Port(COM??)" -> COM??
Match m = reg.Match(name);
string port = m.Groups["port"].Value;
// description : "USB Serial Port"
string desc = (string)obj.GetPropertyValue("Description");
// result string : "COM?? (USB Serial Port)"
list.Add(port + " (" + desc + ")");
}
}
ComPortComparer comp = new ComPortComparer();
list.Sort(comp);
return (string[])list.ToArray(typeof(string));
}
示例10: getNetworkAdapters
/// <summary>
/// Retorna una lista de adaptadores de red disponibles en la máquina
/// Si ocurre un error se arroja una Excepción
/// </summary>
/// <returns></returns>
public static List<NetworkAdapter> getNetworkAdapters()
{
try
{
List<NetworkAdapter> adapters = new List<NetworkAdapter>();
ManagementClass objMC = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection objMOC = objMC.GetInstances();
foreach (ManagementObject objMO in objMOC)
{
if(true)
{
NetworkAdapter adapter = new NetworkAdapter();
adapter.Id = (String)objMO["SettingID"];
adapter.Description = (String)objMO["Description"];
adapter.Index = (UInt32)objMO["Index"];
adapters.Add(adapter);
}
}
return adapters;
}
catch (ThreadAbortException e)
{
throw e;
}
catch (Exception e)
{
throw e;
}
}
示例11: DeviceInformation
public string DeviceInformation(string stringIn)
{
StringBuilder StringBuilder1 = new StringBuilder(string.Empty);
ManagementClass ManagementClass1 = new ManagementClass(stringIn);
//Create a ManagementObjectCollection to loop through
ManagementObjectCollection ManagemenobjCol = ManagementClass1.GetInstances();
//Get the properties in the class
PropertyDataCollection properties = ManagementClass1.Properties;
foreach (ManagementObject obj in ManagemenobjCol)
{
foreach (PropertyData property in properties)
{
try
{
// resit pres pole kde budou nazvy parametru co me zajimaji
if(property.Name.Equals("Name"))
StringBuilder1.AppendLine(property.Name + ": " +
obj.Properties[property.Name].Value.ToString());
}
catch
{
//Add codes to manage more informations
}
}
StringBuilder1.AppendLine();
}
return StringBuilder1.ToString();
}
示例12: GetComputerId
/// <summary>
/// 获取机器码(根据XCore定制的规则)
/// </summary>
/// <returns>当前主机的机器码</returns>
public static String GetComputerId()
{
String DiskDriveid = String.Empty;
String CPUid = String.Empty;
ManagementClass mcdisk = new ManagementClass(strUtil.GetStringByUnicode(@"\u0057\u0069\u006e\u0033\u0032\u005f\u0044\u0069\u0073\u006b\u0044\u0072\u0069\u0076\u0065"));
foreach (ManagementObject mo in mcdisk.GetInstances())
{
DiskDriveid = (string)mo.Properties["Model"].Value;
break;
}
ManagementClass mccpu = new ManagementClass(strUtil.GetStringByUnicode(@"\u0057\u0069\u006e\u0033\u0032\u005f\u0050\u0072\u006f\u0063\u0065\u0073\u0073\u006f\u0072"));
foreach (ManagementObject mo in mccpu.GetInstances())
{
CPUid = (string)mo.Properties["ProcessorId"].Value;
break;
}
Int64 diskid = DiskDriveid.GetHashCode();
Int64 cpuid = CPUid.GetHashCode();
Int64 computerid = ((diskid > 0 ? diskid : -diskid) % 10000000) * ((cpuid > 0 ? cpuid : -cpuid) % 10000000);
if (computerid > 100000000000)
computerid = computerid % 1000000000000;
else if (computerid < 100000000000)
computerid += 100000000000;
return computerid.ToString();
}
示例13: FindMACAddress
public string FindMACAddress()
{
//create out management class object using the
//Win32_NetworkAdapterConfiguration class to get the attributes
//of the network adapter
ManagementClass mgmt = new ManagementClass("Win32_NetworkAdapterConfiguration");
//create our ManagementObjectCollection to get the attributes with
ManagementObjectCollection objCol = mgmt.GetInstances();
string address = String.Empty;
//loop through all the objects we find
foreach (ManagementObject obj in objCol)
{
if (address == String.Empty) // only return MAC Address from first card
{
//grab the value from the first network adapter we find
//you can change the string to an array and get all
//network adapters found as well
//check to see if the adapter's IPEnabled
//equals true
if ((bool)obj["IPEnabled"] == true)
{
address = obj["MacAddress"].ToString();
}
}
//dispose of our object
obj.Dispose();
}
//replace the ":" with an empty space, this could also
//be removed if you wish
address = address.Replace(":", "");
//return the mac address
return address;
}
示例14: CheckDeviceMacadress
public bool CheckDeviceMacadress(string strMacadress)
{
MacAdress = strMacadress;
ManagementPath cmPath = new ManagementPath("root\\sms\\site_PS1:SMS_R_SYSTEM");
ManagementClass cmClass = new ManagementClass(cmPath);
ManagementObjectCollection cmCollection = cmClass.GetInstances();
DeviceFound = false;
foreach (ManagementObject deviceInfo in cmCollection)
{
string[] listCmDeviceMacAdresses = (string[])deviceInfo["MACAddresses"];
foreach (string MacAdressExist in listCmDeviceMacAdresses)
{
if (MacAdressExist == MacAdress)
{
DeviceFound = true;
}
}
}
return DeviceFound;
}
示例15: GetCPUProperties
/// <summary>
/// 获取 CPU 属性参数
/// </summary>
/// <returns>返回 CPU 属性参数</returns>
public static string GetCPUProperties()
{
// Get the WMI class
ManagementClass c = new ManagementClass(new ManagementPath("Win32_Processor"));
// Get the properties in the class
ManagementObjectCollection moc = c.GetInstances();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
// display the properties
sb.AppendLine("Property Names: ");
sb.AppendLine("=================");
foreach (ManagementObject mo in moc)
{
PropertyDataCollection properties = mo.Properties;
//获取内核数代码
sb.AppendLine("物理内核数:" + properties["NumberOfCores"].Value);
sb.AppendLine("逻辑内核数:" + properties["NumberOfLogicalProcessors"].Value);
//其他属性获取代码
foreach (PropertyData property in properties)
{
sb.AppendLine(property.Name + ":" + property.Value);
}
}
string s = sb.ToString();
return s;
}