示例#1
0
        public static string GetMachinePrincipalName()
        {
            string Result = ".";

            try
            {
                ManagementScope localWMI = new ManagementScope(ManagementPath.DefaultPath);
                localWMI.Connect();
                ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
                ManagementObjectSearcher   computerSystemSearcher = null;
                ManagementObjectCollection computerSystemList     = null;
                ManagementObjectEnumerator computerSystemEnum     = null;
                try
                {
                    computerSystemSearcher = new ManagementObjectSearcher(localWMI, query);
                    computerSystemList     = computerSystemSearcher.Get();
                    computerSystemEnum     = computerSystemList.GetEnumerator();
                    if (computerSystemEnum.MoveNext())
                    {
                        var computerSystem = computerSystemEnum.Current;
                        if ((bool)computerSystem["PartOfDomain"])
                        {
                            Result = computerSystem["DNSHostName"].ToString() + "." + computerSystem["Domain"].ToString();
                        }
                        else
                        {
                            Result = computerSystem["DNSHostName"].ToString();
                        }
                    }
                    else
                    {
                        throw new ArgumentNullException("No instances of Win32_ComputerSystem WMI class returned.");
                    }
                }
                finally
                {
                    if (computerSystemEnum != null)
                    {
                        computerSystemEnum.Dispose();
                    }
                    if (computerSystemList != null)
                    {
                        computerSystemList.Dispose();
                    }
                    if (computerSystemSearcher != null)
                    {
                        computerSystemSearcher.Dispose();
                    }
                }
            }
            catch
            {
                Result = Environment.MachineName;
            }
            return(Result);
        }