C#获取计算机信息

C#获取本地计算机信息的总结:

一、调用

 MessageBox.Show("本机的ip地址:" + MySystem.get_ip());
 MessageBox.Show("内存利用率:" + MySystem.get_utilization_rate());
 MessageBox.Show("系统路径:" + MySystem.get_system_path());
 MessageBox.Show("window路径:" + MySystem.get_window_path());
 MessageBox.Show("cpu的id号:" + MySystem.get_CPUID());
 MessageBox.Show("设备硬件卷号:" + MySystem.get_Disk_VolumeSerialNumber());
 MessageBox.Show("本机MAC地址:" + MySystem.get_mac_address());
 MessageBox.Show("邻节点MAC地址:" + MySystem.get_remote_mac("192.168.80.166"));
 MessageBox.Show("硬盘id号:" + MySystem.get_disk_id());
 MessageBox.Show("登陆用户名:" + MySystem.get_user());
 MessageBox.Show("系统类型:" + MySystem.get_SystemType());
 MessageBox.Show("物理总内存:" + MySystem.get_TotalPhysicalMemory());
 MessageBox.Show("电脑名称:" + MySystem.get_ComputerName());
 MessageBox.Show("os版本信息:" + MySystem.get_OSVersion());
 MessageBox.Show("获取CPU信息:" + MySystem.CpuInfo());
 MessageBox.Show("CPU号码:" + MySystem.GetCPUNumber());
 MessageBox.Show("硬盘号码:" + MySystem.GetHardDiskNumber());
 MessageBox.Show("获取内存编号:" + MySystem.GetMemoryNumber());
 MessageBox.Show("获取硬盘信息:" + MySystem.HardDiskInfo());
 MessageBox.Show("获取操作系统信息:" + MySystem.OSInfo());
 MessageBox.Show("获取内存信息:" + MySystem.MemoryInfo());
 MessageBox.Show("获取网卡地址:" + MySystem.NetworkInfo());

二、工具类

namespace ncrmyy.Util
{
    internal enum WmiType
    {
        Win32_Processor,
        Win32_PerfFormattedData_PerfOS_Memory,
        Win32_PhysicalMemory,
        Win32_NetworkAdapterConfiguration,
        Win32_LogicalDisk
    }
    class MySystem
    {
        [DllImport("kernel32")]
        public static extern void GetWindowsDirectory(StringBuilder WinDir, int count);
        [DllImport("kernel32")]
        public static extern void GetSystemDirectory(StringBuilder SysDir, int count);
        [DllImport("kernel32")]
        private static extern void GlobalMemoryStatus(ref StorageInfo memibfo);
        [DllImport("kernel32")]
        public static extern void GetSystemInfo(ref CPUInfo cpuinfo);
        [DllImport("kernel32")]
        public static extern void GetSystemTime(ref SystemTimeInfo stinfo);
        [DllImport("Iphlpapi.dll")]
        public static extern int SendARP(Int32 DestIP,Int32 SrcIP, ref Int64 MacAddr,ref Int32 PhyAddrLen);
        [DllImport("Ws2_32.dll")]
        public static extern Int32 inet_addr(string ipaddr);
        static Dictionary<string, ManagementObjectCollection> WmiDict = new Dictionary<string, ManagementObjectCollection>();

        static MySystem()
        {
            var names = Enum.GetNames(typeof(WmiType));
            foreach (string name in names)
            {
                WmiDict.Add(name, new ManagementObjectSearcher("SELECT FROM " + name).Get());
            }
        }
      
       /// <summary>
        /// 内存信息结构体
       /// </summary>

         [StructLayout(LayoutKind.Sequential)]
        public struct StorageInfo //此处全是以字节为单位
        {
             public uint dwLength;//长度
             public uint dwMemoryLoad;//内存使用率
             public uint dwTotalPhys;//总物理内存
             public uint dwAvailPhys;//可用物理内存
             public uint dwTotalPageFile;//交换文件总大小
             public uint dwAvailPageFile;//可用交换文件大小
             public uint dwTotalVirtual;//总虚拟内存
             public uint dwAvailVirtual;//可用虚拟内存大小
        }
      
        /// <summary>
        /// 系统时间信息结构体
        /// </summary>
        [StructLayout(LayoutKind.Sequential)]
        public struct SystemTimeInfo
        {
            public ushort wYear;
            public ushort wMonth;
            public ushort wDayOfWeek;
            public ushort wDay;
            public ushort wHour;
            public ushort wMinute;
            public ushort wSecond;
            public ushort wMilliseconds;
        }
        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns></returns>
        public static StorageInfo get_StorageInfo()
        {
            StorageInfo memInfor = new StorageInfo();
            GlobalMemoryStatus(ref memInfor);
            return memInfor;
        }
       
        /// <summary>
        /// /获取系统时间信息
        /// </summary>
        /// <returns></returns>
        public static SystemTimeInfo get_SystemTimeInfo()
        {
            SystemTimeInfo memInfor = new SystemTimeInfo();
            GetSystemTime(ref memInfor);
            return memInfor;
        }
        /// <summary>
        /// 获取内存利用率函数
        /// </summary>
        /// <returns></returns>
        public static string get_utilization_rate()
        {
            StorageInfo memInfor = new StorageInfo();
            GlobalMemoryStatus(ref memInfor);
            return memInfor.dwMemoryLoad.ToString("0.0");
        }
        /// <summary>
        /// 获取系统路径
        /// </summary>
        /// <returns></returns>
        public static string get_system_path()
        {
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            GetSystemDirectory(Buff, nChars);
            return Buff.ToString();
        }
        /// <summary>
        /// 获取window路径
        /// </summary>
        /// <returns></returns>
        public static string get_window_path()
        {
            const int nChars = 128;
            StringBuilder Buff = new StringBuilder(nChars);
            GetWindowsDirectory(Buff, nChars);
            return Buff.ToString();
        }
        /// <summary>
        /// 获取cpu的id号
        /// </summary>
        /// <returns></returns>
        public static string get_CPUID()
        {
            try
            {
                string cpuInfo = "";//cpu序列号 
                ManagementClass mc = new ManagementClass("Win32_Processor");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuInfo = mo.Properties["ProcessorId"].Value.ToString();
                }
                moc = null;
                mc = null;
                return cpuInfo;
            }
            catch
            {
                return "unknow";
            }
        }
        /// <summary>
        /// 获取设备硬件卷号
        /// </summary>
        /// <returns></returns>
        public static string get_Disk_VolumeSerialNumber()  
        {  
            ManagementClass mc =new ManagementClass("Win32_NetworkAdapterConfiguration");  
            ManagementObject disk =new ManagementObject("win32_logicaldisk.deviceid="d:"");  
            disk.Get();  
            return disk.GetPropertyValue("VolumeSerialNumber").ToString();  
        }
        /// <summary>
        /// 获取mac地址
        /// </summary>
        /// <returns></returns>
        public static string get_mac_address()
        {
            string mac = "";
            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection moc = mc.GetInstances();
            foreach (ManagementObject mo in moc)
            {
                if ((bool)mo["IPEnabled"] == true)
                {
                    mac = mo["MacAddress"].ToString();
                }
                mo.Dispose();
            }
            return mac;
        }
        /// <summary>
        /// 根据ip获取邻节点MAC地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static string get_remote_mac(string ip)
        {
            StringBuilder mac = new StringBuilder();
            try
            {
                Int32 remote = inet_addr(ip);
                Int64 macinfo = new Int64();
                Int32 length = 6;
                SendARP(remote,0,ref macinfo,ref length);
                string temp = Convert.ToString(macinfo, 16).PadLeft(12, '0').ToUpper();
                int x = 12;
                for (int i = 0; i < 6; i++)
                {
                    if (i == 5)
                        mac.Append(temp.Substring(x - 2, 2));
                    else
                        mac.Append(temp.Substring(x - 2, 2) + "-");
                    x -= 2;
                }
                return mac.ToString();
            }
            catch
            {
                return mac.ToString();
            }
        }
        /// <summary>
        /// 获取本机的ip地址
        /// </summary>
        /// <returns></returns>
        public static string get_ip()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        //st=mo["IpAddress"].ToString(); 
                        System.Array ar;
                        ar = (System.Array)(mo.Properties["IpAddress"].Value);
                        st = ar.GetValue(0).ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        /// <summary>
        /// 获取硬盘id号
        /// </summary>
        /// <returns></returns>
        public static string get_disk_id()
        {
            try
            {
                String HDid = "";
                ManagementClass mc = new ManagementClass("Win32_DiskDrive");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    HDid = (string)mo.Properties["Model"].Value;
                }
                moc = null;
                mc = null;
                return HDid;
            }
            catch
            {
                return "unknow";
            }
        }
        /// <summary>
        /// 获得系统登陆用户名
        /// </summary>
        /// <returns></returns>
        public static string get_user()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["UserName"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        /// <summary>
        /// 获得系统类型
        /// </summary>
        /// <returns></returns>
        public static string get_SystemType()
        {
            try
            {
                string st = "";
                ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    st = mo["SystemType"].ToString();
                }
                moc = null;
                mc = null;
                return st;
            }
            catch
            {
                return "unknow";
            }
        }
        /// <summary>
        /// 获得物理总内存
        /// </summary>
        /// <returns></returns>
        public static string get_TotalPhysicalMemory()
          {
              try
              {
                  string st = "";
                  ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
                  ManagementObjectCollection moc = mc.GetInstances();
                  foreach (ManagementObject mo in moc)
                  {
                      st = mo["TotalPhysicalMemory"].ToString();
                  }
                  moc = null;
                  mc = null;
                  return st;
              }
              catch
              {
                  return "unknow";
              }
          }
        /// <summary>
        /// 获得电脑名称
        /// </summary>
        /// <returns></returns>
        public static string get_ComputerName()
         {
             try
             {
                 return System.Environment.GetEnvironmentVariable("ComputerName");
             }
             catch
             {
                 return "unknow";
             }
         }
        /// <summary>
        /// 获取os版本信息
        /// </summary>
        /// <returns></returns>

        public static string get_OSVersion()
        {
            System.OperatingSystem version = System.Environment.OSVersion;
            switch (version.Platform)
            {
                case System.PlatformID.Win32Windows:
                    switch (version.Version.Minor)
                    {
                        case 0:
                            return "Windows 95";
                        case 10:
                            if (version.Version.Revision.ToString() == "2222A")
                                return "Windows 98 Second Edition";
                            else
                                return "Windows 98";
                        case 90:
                            return "Windows Me";
                    }
                    break;
                case System.PlatformID.Win32NT:
                    switch (version.Version.Major)
                    {
                        case 3:
                            return "Windows NT 3.51";
                        case 4:
                            return "Windows NT 4.0";
                        case 5:
                            if (version.Version.Minor == 0)
                                return "Windows 2000";
                            else
                                return "Windows XP";
                        case 6:
                            return "Windows 7";
                        case 10: 
                              return "Windows 10";
                    }
                    break;
            }
            return "发现失败";

        }
        /// <summary>
        /// 获取硬盘号码
        /// </summary>
        /// <returns></returns>
        public static string GetHardDiskNumber()
        {
            var query = WmiDict[WmiType.Win32_LogicalDisk.ToString()];
            //var collection = query.Get();

            string result = string.Empty;
            foreach (var obj in query)
            {
                result = obj["VolumeSerialNumber"].ToString();
                break;
            }

            return result;
        }

        /// <summary>
        /// 获取CPU号码
        /// </summary>
        /// <returns></returns>
        public static string GetCPUNumber()
        {
            var query = WmiDict[WmiType.Win32_Processor.ToString()];
            //var collection = query.Get();

            string result = string.Empty;
            foreach (var obj in query)
            {
                result = obj["Processorid"].ToString();
                break;
            }

            return result;
        }

        /// <summary>
        /// 获取内存编号
        /// </summary>
        /// <returns></returns>
        public static string GetMemoryNumber()
        {
            var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()];
            //var collection = query.Get();

            string result = string.Empty;
            foreach (var obj in query)
            {
                result = obj["PartNumber"].ToString();
                break;
            }
            return result;
        }
        /// <summary>
        /// 获取硬盘信息
        /// </summary>
        /// <returns></returns>
        public static string HardDiskInfo()
        {
            DriveInfo[] drives = DriveInfo.GetDrives();
            StringBuilder sr = new StringBuilder();
            foreach (DriveInfo drive in drives)
            {
                if (drive.IsReady)
                {
                    var val1 = (double)drive.TotalSize / 1024 / 1024;
                    var val2 = (double)drive.TotalFreeSpace / 1024 / 1024;
                    sr.AppendFormat("{0}:{2}/{3}MB/{4}MB/{1}%可用;",
                        drive.Name,
                        string.Format("{0:F2}", val2 / val1 100),
                        drive.DriveFormat,
                        (long)val1,
                        (long)val2);
                }
            }
            return sr.ToString();
        }

        /// <summary>
        /// 获取操作系统信息
        /// </summary>
        /// <returns></returns>
        public static string OSInfo()
        {
            StringBuilder sr = new StringBuilder();
            sr.AppendFormat("机器名:{0};操作系统:{1};系统文件夹:{2};语言:{3};.NET:{4};当前目录:{5};当前用户:{6};",
                Environment.MachineName,
                Environment.OSVersion,
                Environment.SystemDirectory,
                CultureInfo.InstalledUICulture.EnglishName,
                Environment.Version,
                Environment.CurrentDirectory,
                Environment.UserName);
            return sr.ToString();
        }

        /// <summary>
        /// 获取网卡信息
        /// </summary>
        /// <returns></returns>
        public static string NetworkInfo()
        {
            StringBuilder sr = new StringBuilder();

            string host = Dns.GetHostName();
            IPHostEntry ipEntry = Dns.GetHostByName(host);
            sr.Append("IPv4:" + ipEntry.AddressList[0] + "/");

            sr.Append("IPv6:");
            ipEntry = Dns.GetHostEntry(host);
            sr.Append("IPv6:" + ipEntry.AddressList[0] + ";");

            sr.Append("MAC:");
            var query = WmiDict[WmiType.Win32_NetworkAdapterConfiguration.ToString()];
            foreach (var obj in query)
            {
                if (obj["IPEnabled"].ToString() == "True")
                    sr.Append(obj["MacAddress"] + ";");
            }

            return sr.ToString();
        }

        /// <summary>
        /// 获取内存信息
        /// </summary>
        /// <returns></returns>
        public static string MemoryInfo()
        {
            StringBuilder sr = new StringBuilder();
            long capacity = 0;
            var query = WmiDict[WmiType.Win32_PhysicalMemory.ToString()];
            int index = 1;
            foreach (var obj in query)
          {
                capacity += Convert.ToInt64(obj["Capacity"]);
                index++;
            }
            sr.Append("总物理内存:");
            sr.Append(capacity / 1024 / 1024 + "MB;");

            query = WmiDict[WmiType.Win32_PerfFormattedData_PerfOS_Memory.ToString()];
            sr.Append("总可用内存:");
            long available = 0;
            foreach (var obj in query)
            {
                available += Convert.ToInt64(obj.Properties["AvailableMBytes"].Value);
            }
            sr.Append(available + "MB;");
            sr.AppendFormat("{0:F2}%可用; ", (double)available / (capacity / 1024 / 1024) 100);

            return sr.ToString();
        }

        /// <summary>
        /// 获取CPU信息
        /// </summary>
        /// <returns></returns>
        public static string CpuInfo()
        {
            StringBuilder sr = new StringBuilder();

            var query = WmiDict[WmiType.Win32_Processor.ToString()];
            foreach (var obj in query)
            {
                sr.Append("厂商:" + obj["Manufacturer"] + ";");
                sr.Append("产品名称:" + obj["Name"] + ";");
                sr.Append("最大频率:" + obj["MaxClockSpeed"] + ";");
                sr.Append("当前频率:" + obj["CurrentClockSpeed"] + ";");
            }

            return sr.ToString();
        }



        /// <summary>
        /// 获取CPU信息产品名称
        /// </summary>
        /// <returns></returns>
        public static string Cpu_cpmc_Info()
        {
            StringBuilder sr = new StringBuilder();

            var query = WmiDict[WmiType.Win32_Processor.ToString()];
            foreach (var obj in query)
            {

                sr.Append(obj["Name"]);

            }

            return sr.ToString();
        }
    }
}

C#获取计算机信息

版权声明:本文内容由互联网用户投稿发布,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2211788188@qq.com 举报,一经查实,本站将立刻删除。如需转载请注明出处:https://www.wptmall.com/a/article/19106

为您推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注