• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Management.ObjectQuery类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Management.ObjectQuery的典型用法代码示例。如果您正苦于以下问题:C# ObjectQuery类的具体用法?C# ObjectQuery怎么用?C# ObjectQuery使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



ObjectQuery类属于System.Management命名空间,在下文中一共展示了ObjectQuery类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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());
                 }
             }
         }
     }
 }
开发者ID:JKLFA,项目名称:Craig-s-Utility-Library,代码行数:32,代码来源:OperatingSystem.cs


示例2: GetPhysicalCores

        /// <summary>
        /// Gets the physcial cores and should this fail returns the Environment.ProcessorCount
        /// that can also include logical cores.
        /// </summary>
        /// <returns>core count.</returns>
        public static uint GetPhysicalCores()
        {
            try
            {
                ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");
                ObjectQuery query = new ObjectQuery("SELECT NumberOfCores FROM Win32_Processor");

                ManagementObjectSearcher searcher =
                            new ManagementObjectSearcher(scope, query);

                ManagementObjectCollection queryCollection = searcher.Get();
                var enumerator = queryCollection.GetEnumerator();
                if (enumerator.MoveNext())
                {
                    ManagementObject obj = (ManagementObject)enumerator.Current;
                    return (uint)obj["NumberOfCores"];
                }
                else
                    return (uint)Environment.ProcessorCount;
            }
            // We are not very interested in throwing the exception, we might log it
            // but this carries little information as if WMI fails there is very little
            // that the we or the user can do to provide the correct information.
            catch
            {
                return (uint)Environment.ProcessorCount;
            }
        }
开发者ID:JackWangCUMT,项目名称:SCPM,代码行数:33,代码来源:Unsafe.cs


示例3: 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;
        }
开发者ID:5dollartools,项目名称:NAM,代码行数:31,代码来源:Disk.cs


示例4: GetOSDetails

        public static List<EntOS> GetOSDetails(ManagementScope scope)
        {
            _logger.Info("Collecting OS details for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntOS> lstOS = new List<EntOS>();

            try
            {
                query = new ObjectQuery("Select * from Win32_OperatingSystem");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstOS.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstOS.Add(FillDetails(obj));
                    obj.Dispose();
                }
            }
            catch (System.Exception e)
            {
                _logger.Error("Exception in OS collection " + e.Message);
            }
            finally
            {
                searcher.Dispose();
            }
            return lstOS;
        }
开发者ID:5dollartools,项目名称:NAM,代码行数:31,代码来源:OS.cs


示例5: GetDefaultPrinterName

        public static String GetDefaultPrinterName()
        {
            {
                var query = new ObjectQuery("SELECT * FROM Win32_Printer");
                var searcher = new ManagementObjectSearcher(query);

                foreach (ManagementObject mo in searcher.Get())
                {
                    if (((bool?)mo["Default"]) ?? false)
                    {
                        string whole = mo["Name"] as string;

                        if (whole.Contains("opsprint"))
                        {
                            string[] actual;
                            actual = whole.Split('\\');
                            return actual[3];
                        }
                        else if (whole.Contains("Fax") || whole.Contains("XPS") || whole.Contains("OneNote"))
                            return "none";
                        else return whole;
                    }
                }

                return null;
            }
        }
开发者ID:kaburkett,项目名称:Windows-Password-Reminder,代码行数:27,代码来源:QueryPrinter.cs


示例6: GetHotfixDetails

        public static List<EntHotfixes> GetHotfixDetails(ManagementScope scope)
        {
            _logger.Info("Collecting hotfix for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntHotfixes> lstHotfix = new List<EntHotfixes>();

            try
            {
                query = new ObjectQuery("Select * from Win32_QuickFixEngineering");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstHotfix.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstHotfix.Add(FillDetails(obj));
                    obj.Dispose();
                }
            }
            catch (System.Exception e)
            {
                _logger.Error("Exception is hotfix collection " + e.Message);
            }
            finally
            {
                searcher.Dispose();
            }
            return lstHotfix;
        }
开发者ID:5dollartools,项目名称:NAM,代码行数:31,代码来源:Hotfix.cs


示例7: GetCOMPortsInfo

        public static List<COMPortFinder> GetCOMPortsInfo()
        {
            List<COMPortFinder> COMPortFinderList = new List<COMPortFinder>();

            ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
            ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");

            ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
            ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);

            using (comPortSearcher)
            {
                string caption = null;
                foreach (ManagementObject obj in comPortSearcher.Get())
                {
                    if (obj != null)
                    {
                        object captionObj = obj["Caption"];
                        if (captionObj != null)
                        {
                            caption = captionObj.ToString();
                            if (caption.Contains("(COM"))
                            {
                                COMPortFinder COMPortFinder = new COMPortFinder();
                                COMPortFinder.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")",
                                                                     string.Empty);
                                COMPortFinder.Description = caption;
                                COMPortFinderList.Add(COMPortFinder);
                            }
                        }
                    }
                }
            }
            return COMPortFinderList;
        }
开发者ID:donnaknew,项目名称:programmingProject,代码行数:35,代码来源:COMPortFinder.cs


示例8: isAdmin

        public static bool isAdmin(string processName)
        {
            string ProcessOwner = "";
            string ProcessDomain = "";

            System.Management.ObjectQuery x = new System.Management.ObjectQuery("Select * From Win32_Process where Name='" + processName + ".exe" + "'");
            System.Management.ManagementObjectSearcher mos = new System.Management.ManagementObjectSearcher(x);
            foreach (System.Management.ManagementObject mo in mos.Get())
            {
                string[] s = new string[2];
                mo.InvokeMethod("GetOwner", (object[])s);
                ProcessOwner = s[0].ToString();
                ProcessDomain = s[1].ToString();
                break;
            }

            string userPath = ProcessDomain + "/" + ProcessOwner;

            using (DirectoryEntry groupEntry = new DirectoryEntry("WinNT://./Administrators,group"))
            {
                foreach (object member in (IEnumerable)groupEntry.Invoke("Members"))
                {
                    using (DirectoryEntry memberEntry = new DirectoryEntry(member))
                    {
                        Console.WriteLine(memberEntry.Path);
                        if (memberEntry.Path.Contains(userPath))
                        {
                            return true;
                        }
                    }
                }
            }
            return false;
        }
开发者ID:hfenigma,项目名称:d3adventure,代码行数:34,代码来源:ProcessTools.cs


示例9: DeleteShare

        public void DeleteShare(IShareDescriptor descriptor)
        {
            var wqlQuery = new ObjectQuery(string.Format(@"SELECT * from Win32_Share WHERE Name = '{0}'", descriptor.Name));

            ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(_managementClass.Scope, wqlQuery);
            ManagementObjectCollection shareObjectsCollection = objectSearcher.Get();

            if (shareObjectsCollection.Count == 0)
            {
                throw new ShareInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_ShareNotFound, descriptor.Name);
            }

            foreach (ManagementObject shareObject in shareObjectsCollection)
            {
                PropertyDataCollection outParams;
                long returnValue;

                var inParamsCollection = new List<PropertyDataObject>();
                inParamsCollection.Add(new PropertyDataObject() { Name = "Reason", Value = (uint)0 });

                _handler.Handle("Terminate", inParamsCollection, out outParams);

                returnValue = long.Parse(outParams["ReturnValue"].Value.ToString());

                if (returnValue != 0)
                {
                    throw new ShareInstrumentationException(@"{0} {1}.", ExceptionMessages.Win32_ShareFail, _errorMessageProvider.GetErrorMessage(ErrorMessageProvider.ErrorClass.Win32_Share, returnValue));
                }
            }
        }
开发者ID:danni95,项目名称:Core,代码行数:30,代码来源:ShareInstrumentation.cs


示例10: DisplayRam

        private void DisplayRam(object sender, EventArgs e)
        {
            //In thong so trong tabMemry
            ManagementScope oMs = new ManagementScope();
            ObjectQuery oQuery = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
            ManagementObjectCollection oCollection = oSearcher.Get();

            long MemSize = 0;
            long mCap = 0;
            long FreePhysicalMemory = 0;

            // In case more than one Memory sticks are installed
            foreach (ManagementObject obj in oCollection)
            {
                mCap = Convert.ToInt64(obj["Capacity"]);
                MemSize += mCap;
            }
            MemSize = (MemSize / 1024) / 1024;
            txtRam.Text = MemSize.ToString() + "  MB";

            // Get info RAM availble
            ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_OperatingSystem");
            foreach (ManagementObject tmp in searcher.Get())
            {
                FreePhysicalMemory = Convert.ToInt64(tmp["FreePhysicalMemory"]);
            }
            FreePhysicalMemory = (FreePhysicalMemory) / 1024;
            txtRamAvai.Text = FreePhysicalMemory.ToString() + "  MB";
        }
开发者ID:neittien0110,项目名称:Project-2,代码行数:30,代码来源:FormCPU-T.cs


示例11: getComputerInfos

        public static String[] getComputerInfos(string computername)
        {
            String[] computerInfos = new String[2];

            ConnectionOptions connOptions = new ConnectionOptions();
            ObjectGetOptions objectGetOptions = new ObjectGetOptions();
            ManagementPath managementPath = new ManagementPath("Win32_Process");

            //To use caller credential
            connOptions.Impersonation = ImpersonationLevel.Impersonate;
            connOptions.EnablePrivileges = true;
            ManagementScope manScope = new ManagementScope(String.Format(@"\\{0}\ROOT\CIMV2", computername), connOptions);
            manScope.Connect();
            ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(manScope, query);
            ManagementObjectCollection queryCollection = searcher.Get();

            foreach (ManagementObject m in queryCollection){

                computerInfos[0] = Convert.ToString(m["Caption"]);
                computerInfos[1] = Convert.ToString(m["Status"]);

            }

            return computerInfos;
        }
开发者ID:banctilrobitaille,项目名称:RemoteScriptLauncher,代码行数:26,代码来源:CommUtility.cs


示例12: getUID

        public static String getUID()
        {
            try
            {
                ManagementScope theScope = new ManagementScope("\\\\" + Environment.MachineName + "\\root\\cimv2");
                StringBuilder theQueryBuilder = new StringBuilder();
                theQueryBuilder.Append("SELECT MACAddress FROM Win32_NetworkAdapter");
                ObjectQuery theQuery = new ObjectQuery(theQueryBuilder.ToString());
                ManagementObjectSearcher theSearcher = new ManagementObjectSearcher(theScope, theQuery);
                ManagementObjectCollection theCollectionOfResults = theSearcher.Get();

                foreach (ManagementObject theCurrentObject in theCollectionOfResults)
                {
                    if (theCurrentObject != null && theCurrentObject["MACAddress"] != null)
                    {
                        return theCurrentObject["MACAddress"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                return "undefined";
            }
            return "undefined";
        }
开发者ID:peppy,项目名称:sgl4cs,代码行数:25,代码来源:ErrorReporter.cs


示例13: UpdateCameraList

        /// <summary>
        /// Updates the list of cameras
        /// </summary>
        /// <returns>The list of cameras</returns>
        public static ManagementObjectCollection UpdateCameraList()
        {
                    
            //Searches for the device using its name
            ObjectQuery oq = new System.Management.ObjectQuery("select * from Win32_PnPEntity where Name='NaturalPoint OptiTrack V100'");
            ManagementObjectSearcher query = new ManagementObjectSearcher(oq);
            ManagementObjectCollection queryCollection = query.Get();
            /*
            Console.WriteLine();
            Console.WriteLine("Number of Cameras : " + queryCollection.Count);
            if (queryCollection.Count > 0)
            {
                foreach (ManagementObject mo in queryCollection)
                {
                    Console.WriteLine();
                    Console.WriteLine("USB Camera");

                    

                    foreach (PropertyData propertyData in mo.Properties)
                    {
                       

                        Console.WriteLine("Property Name = " + propertyData.Name);

                        Console.WriteLine("Property Value = " + propertyData.Value);

                    }
                    
                }
            }
            */
            return queryCollection;
        }
开发者ID:matalangilbert,项目名称:stromohab-2008,代码行数:38,代码来源:WMIDevices.cs


示例14: ObjectQuery

        public static List<EntStartUp>GetStartUpDetails(ManagementScope scope)
        {
            _logger.Info("Collecting startup details for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntStartUp> lstStartUp = new List<EntStartUp>();

            try
            {
                query = new ObjectQuery("select * from Win32_StartupCommand where User != '.DEFAULT' and User != 'NT AUTHORITY\\\\SYSTEM'");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstStartUp.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstStartUp.Add(FillDetails(obj));
                    obj.Dispose();
                }

            }
            catch (System.Exception e)
            {
                _logger.Error("Exception in startup collection " + e.Message);
            }
            finally
            {
                searcher.Dispose();
            }
            return lstStartUp;
        }
开发者ID:5dollartools,项目名称:NAM,代码行数:32,代码来源:StartUp.cs


示例15: GetFilesWithExtension

 /// <summary>
 /// Gets a list of files on the machine with a specific extension
 /// </summary>
 /// <param name="Computer">Computer to search</param>
 /// <param name="UserName">User name (if not local)</param>
 /// <param name="Password">Password (if not local)</param>
 /// <param name="Extension">File extension to look for</param>
 /// <returns>List of files that are found to have the specified extension</returns>
 public static IEnumerable<string> GetFilesWithExtension(string Computer, string UserName, string Password, string Extension)
 {
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Computer), "Computer");
     Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(Extension), "Extension");
     List<string> Files = new List<string>();
     ManagementScope Scope = null;
     if (!string.IsNullOrEmpty(UserName) && !string.IsNullOrEmpty(Password))
     {
         ConnectionOptions Options = new ConnectionOptions();
         Options.Username = UserName;
         Options.Password = Password;
         Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2", Options);
     }
     else
     {
         Scope = new ManagementScope("\\\\" + Computer + "\\root\\cimv2");
     }
     Scope.Connect();
     ObjectQuery Query = new ObjectQuery("SELECT * FROM CIM_DataFile where Extension='" + Extension + "'");
     using (ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Scope, Query))
     {
         using (ManagementObjectCollection Collection = Searcher.Get())
         {
             foreach (ManagementObject TempBIOS in Collection)
             {
                 Files.Add(TempBIOS.Properties["Drive"].Value.ToString()+TempBIOS.Properties["Path"].Value.ToString()+TempBIOS.Properties["FileName"].Value.ToString());
             }
         }
     }
     return Files;
 }
开发者ID:kaytie,项目名称:Craig-s-Utility-Library,代码行数:39,代码来源:Files.cs


示例16: tsbRun_Click

        private void tsbRun_Click(object sender, EventArgs e)
        {
            SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
            foreach (ManagementObject os in searcher.Get())
            {
                this.txtResult.AppendText(os["Name"] + ";");
            }
            this.txtResult.AppendText("\r\n");

            //连接远程计算机
            ConnectionOptions co = new ConnectionOptions();
            co.Username = "administrator";
            co.Password = "123qwe!";
            System.Management.ManagementScope ms = new System.Management.ManagementScope("\\\\192.168.100.51\\root\\cimv2", co);
            //查询远程计算机
            System.Management.ObjectQuery oq = new System.Management.ObjectQuery("SELECT * FROM Win32_OperatingSystem");

            ManagementObjectSearcher query1 = new ManagementObjectSearcher(ms, oq);
            ManagementObjectCollection queryCollection1 = query1.Get();
            foreach (ManagementObject mo in queryCollection1)
            {
                string[] ss = { "" };
                mo.InvokeMethod("Reboot", ss);
                this.txtResult.AppendText(mo.ToString());
            }
        }
开发者ID:fanjun365,项目名称:TheDbgTool,代码行数:27,代码来源:WMIForm.cs


示例17: checkAntiVirus

        public static List<Object[]> checkAntiVirus()
        {
            List<Object[]> av = new List<Object[]>();
            ConnectionOptions _connectionOptions = new ConnectionOptions();

            _connectionOptions.EnablePrivileges = true;
            _connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
            ManagementScope _managementScope = new ManagementScope(string.Format("\\\\{0}\\root\\SecurityCenter2", "localhost"), _connectionOptions);
            _managementScope.Connect();

            ObjectQuery _objectQuery = new ObjectQuery("SELECT * FROM AntivirusProduct");
            ManagementObjectSearcher _managementObjectSearcher = new ManagementObjectSearcher(_managementScope, _objectQuery);
            ManagementObjectCollection _managementObjectCollection = _managementObjectSearcher.Get();

            if (_managementObjectCollection.Count > 0)
            {
                Boolean updated = false;
                foreach (ManagementObject item in _managementObjectCollection)
                {
                    updated = (item["productState"].ToString() == "266240" || item["productState"].ToString() == "262144");
                    av.Add(new Object[] { item["displayName"].ToString(), updated });
                }
            }

            return av;
        }
开发者ID:jra89,项目名称:ass,代码行数:26,代码来源:WindowsSecurityChecks.cs


示例18: start

 /// <summary>
 /// Attempts to start the selected process. - BC
 /// </summary>
 /// <returns>Return value of the attempted command.</returns>
 public static int start(String program)
 {
     //MRM Get a list of all programs installed and basic information about them from Windows
     ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_Product");
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
     ManagementObjectCollection collection = searcher.Get();
     //MRM The closest filename and the full path to the file
     String full = null;
     String closest = null;
     //MRM Loop through all the programs installed
     foreach (ManagementObject mObject in collection)
     {
         //MRM See if this is the correct program to be looking at
         if (((String)mObject["name"]).ToLower() == program.ToLower() && (String)mObject["InstallLocation"] != null)
         {
             //MRM Get the install location for the application since it is the one we are looking for
             String[] fileNames = System.IO.Directory.GetFiles((String)mObject["InstallLocation"]);
             foreach (String fileName in fileNames)
             {
                 //MRM Grab the actual filename to check
                 String[] fileSplit = fileName.Split('\\');
                 String file = fileSplit[fileSplit.Length - 1];
                 //MRM Make sure the file is executable and is not meant for updating or installing the application
                 if (file.Contains(".exe") && file.Substring(file.Length-4) == ".exe" && (!file.ToLower().Contains("update") && !file.ToLower().Contains("install")))
                 {
                     //MRM Replace all underscored with spaces to make it more towards the normal file naming convention
                     file = file.Replace("_", " ");
                     //MRM Get the first part of the file before any extension of . due to standard naming conventions
                     String[] fileNonTypes = file.Split('.');
                     file = fileNonTypes[0];
                     //MRM If there is no guess assume we are correct for now
                     if (closest == null)
                     {
                         full = fileName;
                         closest = file;
                     }
                     //MRM Else if the current file is closer than our previous guess, select that file
                     else if (Math.Abs(program.CompareTo(closest)) >= Math.Abs(program.CompareTo(file)))
                     {
                         full = fileName;
                         closest = file;
                     }
                 }
             }
             break;
         }
     }
     //MRM If we have found an adequte file to launch, launch the file.
     if (full != null)
     {
         //MRM Start a process with the correct information
         Process p = new Process();
         p.StartInfo.RedirectStandardOutput = false;
         p.StartInfo.RedirectStandardInput = false;
         p.StartInfo.FileName = full;
         p.Start();
         return 1;
     }
     return -1;
 }
开发者ID:mueschm,项目名称:WIT-InControl,代码行数:64,代码来源:ProcessManager.cs


示例19: GetManagementObjects

        static IEnumerable<byte[]> GetManagementObjects()
        {
            var options = new EnumerationOptions {Rewindable = false, ReturnImmediately = true};
            var scope = new ManagementScope(ManagementPath.DefaultPath);
            var query = new ObjectQuery("SELECT * FROM Win32_NetworkAdapter");

            var searcher = new ManagementObjectSearcher(scope, query, options);
            ManagementObjectCollection collection = searcher.Get();

            foreach (ManagementObject obj in collection)
            {
                byte[] bytes;
                try
                {
                    PropertyData propertyData = obj.Properties["MACAddress"];
                    string propertyValue = propertyData.Value.ToString();

                    bytes = propertyValue.Split(':')
                        .Select(x => byte.Parse(x, NumberStyles.HexNumber))
                        .ToArray();
                }
                catch (Exception)
                {
                    continue;
                }

                if (bytes.Length == 6)
                    yield return bytes;
            }
        }
开发者ID:Xamarui,项目名称:NewId,代码行数:30,代码来源:WMINetworkAddressWorkerIdProvider.cs


示例20: DiskUsage

        private static Dictionary<string, double> DiskUsage()
        {
            Dictionary<string, double> temp = new Dictionary<string, double>();

            double freeSpace = 0;
            double usedSpace = 0;

            // get disk stats
            System.Management.ObjectQuery oQuery = new System.Management.ObjectQuery("select FreeSpace,Size,Name from Win32_LogicalDisk where DriveType=3");
            ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oQuery);
            ManagementObjectCollection oReturnCollection = oSearcher.Get();

            //loop through found drives and write out info
            foreach (ManagementObject oReturn in oReturnCollection)
            {
                //Free space in MB
                freeSpace += Convert.ToInt64(oReturn["FreeSpace"]);

                //Used space in MB
                usedSpace += (Convert.ToInt64(oReturn["Size"]) - Convert.ToInt64(oReturn["FreeSpace"]));
            }
            temp.Add("used", usedSpace);
            temp.Add("free", freeSpace);

            return temp;
        }
开发者ID:joshrendek,项目名称:servly-agents,代码行数:26,代码来源:Servly.cs



注:本文中的System.Management.ObjectQuery类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Management.Path类代码示例发布时间:2022-05-26
下一篇:
C# Management.ObjectGetOptions类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap