當前位置: 首頁>>代碼示例>>C#>>正文


C# Management.ManagementClass類代碼示例

本文整理匯總了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;
            }
        }
開發者ID:davidduffett,項目名稱:dropkick,代碼行數:29,代碼來源:WmiProcess.cs

示例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);
            }
        }
開發者ID:jcw-,項目名稱:sparrowtoolkit,代碼行數:34,代碼來源:ViewModel.cs

示例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");
            }
        }
開發者ID:Porterbg,項目名稱:Freeflex,代碼行數:25,代碼來源:Core.cs

示例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;
        }
開發者ID:Jeremiahf,項目名稱:wix3,代碼行數:39,代碼來源:FileUtilities.cs

示例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;
        }
開發者ID:fr4gles,項目名稱:Building-Blocks,代碼行數:31,代碼來源:HardwareIdentifiers.cs

示例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);
            }
        }
開發者ID:StealFocus,項目名稱:Core,代碼行數:32,代碼來源:SendHandler.cs

示例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));

                    }
                }
            }
        }
開發者ID:suleymansahin07,項目名稱:NoCableLauncher,代碼行數:29,代碼來源:Settings.cs

示例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();
 }
開發者ID:huaminglee,項目名稱:yousoftbath,代碼行數:8,代碼來源:RegisterForm.cs

示例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));
        }
開發者ID:yoggy,項目名稱:enumcomport,代碼行數:32,代碼來源:EnumComPort.cs

示例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;
     }
 }
開發者ID:uriel291029,項目名稱:High-Level-MANET-Protocol,代碼行數:34,代碼來源:SystemHandler.cs

示例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();
 }
開發者ID:VojtechSindler,項目名稱:HoperInfo,代碼行數:28,代碼來源:Device_information.cs

示例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();
 }
開發者ID:mfz888,項目名稱:xcore,代碼行數:29,代碼來源:Util.cs

示例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;
 }
開發者ID:BjkGkh,項目名稱:Custom-R2,代碼行數:33,代碼來源:LicenceProvider.cs

示例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;
        }
開發者ID:aramiz84,項目名稱:sllCreateComputer,代碼行數:27,代碼來源:CheckMacAdress.cs

示例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;
        }
開發者ID:cheehwasun,項目名稱:BaiduPCS_NET,代碼行數:30,代碼來源:Utils.cs


注:本文中的System.Management.ManagementClass類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。