c#中如何获取本机MAC地址、IP地址、硬盘ID、CPU序列号等系统信息
-
我们在利用C#开发桌面程序(Winform)程序的时候,经常需要获取一些跟系统相关的信息,例如用户名、MAC地址、IP地址、硬盘ID、CPU序列号、系统名称、物理内存等。
首先需要引入命名空间:
- using System.Management;
- /// 获取本机用户名、MAC地址、内网IP地址、公网IP地址、硬盘ID、CPU序列号、系统名称、物理内存。
- /// </summary>
- public class GetSystemInfo
- {
- /// <summary>
- /// 操作系统的登录用户名
- /// </summary>
- /// <returns>系统的登录用户名</returns>
- public static string GetUserName()
- {
- try
- {
- string strUserName = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- strUserName = mo["UserName"].ToString();
- }
- moc = null;
- mc = null;
- return strUserName;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取本机MAC地址
- /// </summary>
- /// <returns>本机MAC地址</returns>
- public static string GetMacAddress()
- {
- try
- {
- string strMac = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- if ((bool)mo["IPEnabled"] == true)
- {
- strMac = mo["MacAddress"].ToString();
- }
- }
- moc = null;
- mc = null;
- return strMac;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取本机的物理地址
- /// </summary>
- /// <returns></returns>
- public static string getMacAddr_Local()
- {
- string madAddr = null;
- try
- {
- ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
- ManagementObjectCollection moc2 = mc.GetInstances();
- foreach (ManagementObject mo in moc2)
- {
- if (Convert.ToBoolean(mo["IPEnabled"]) == true)
- {
- madAddr = mo["MacAddress"].ToString();
- madAddr = madAddr.Replace(':', '-');
- }
- mo.Dispose();
- }
- if (madAddr == null)
- {
- return "unknown";
- }
- else
- {
- return madAddr;
- }
- }
- catch (Exception)
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取客户端内网IPv6地址
- /// </summary>
- /// <returns>客户端内网IPv6地址</returns>
- public static string GetClientLocalIPv6Address()
- {
- string strLocalIP = string.Empty;
- try
- {
- IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
- IPAddress ipAddress = ipHost.AddressList[0];
- strLocalIP = ipAddress.ToString();
- return strLocalIP;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取客户端内网IPv4地址
- /// </summary>
- /// <returns>客户端内网IPv4地址</returns>
- public static string GetClientLocalIPv4Address()
- {
- string strLocalIP = string.Empty;
- try
- {
- IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
- IPAddress ipAddress = ipHost.AddressList[0];
- strLocalIP = ipAddress.ToString();
- return strLocalIP;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取客户端内网IPv4地址集合
- /// </summary>
- /// <returns>返回客户端内网IPv4地址集合</returns>
- public static List<string> GetClientLocalIPv4AddressList()
- {
- List<string> ipAddressList = new List<string>();
- try
- {
- IPHostEntry ipHost = Dns.Resolve(Dns.GetHostName());
- foreach (IPAddress ipAddress in ipHost.AddressList)
- {
- if (!ipAddressList.Contains(ipAddress.ToString()))
- {
- ipAddressList.Add(ipAddress.ToString());
- }
- }
- }
- catch
- {
- }
- return ipAddressList;
- }
- /// <summary>
- /// 获取客户端外网IP地址
- /// </summary>
- /// <returns>客户端外网IP地址</returns>
- public static string GetClientInternetIPAddress()
- {
- string strInternetIPAddress = string.Empty;
- try
- {
- using (WebClient webClient = new WebClient())
- {
- strInternetIPAddress = webClient.DownloadString("http://www.coridc.com/ip");
- Regex r = new Regex("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}");
- Match mth = r.Match(strInternetIPAddress);
- if (!mth.Success)
- {
- strInternetIPAddress = GetClientInternetIPAddress2();
- mth = r.Match(strInternetIPAddress);
- if (!mth.Success)
- {
- strInternetIPAddress = "unknown";
- }
- }
- return strInternetIPAddress;
- }
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取本机公网IP地址
- /// </summary>
- /// <returns>本机公网IP地址</returns>
- private static string GetClientInternetIPAddress2()
- {
- string tempip = "";
- try
- {
- //http://iframe.ip138.com/ic.asp 返回的是:您的IP是:[220.231.17.99] 来自:北京市 光环新网
- WebRequest wr = WebRequest.Create("http://iframe.ip138.com/ic.asp");
- Stream s = wr.GetResponse().GetResponseStream();
- StreamReader sr = new StreamReader(s, Encoding.Default);
- string all = sr.ReadToEnd(); //读取网站的数据
- int start = all.IndexOf("[") + 1;
- int end = all.IndexOf("]", start);
- tempip = all.Substring(start, end - start);
- sr.Close();
- s.Close();
- return tempip;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取硬盘序号
- /// </summary>
- /// <returns>硬盘序号</returns>
- public static string GetDiskID()
- {
- try
- {
- string strDiskID = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_DiskDrive");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- strDiskID = mo.Properties["Model"].Value.ToString();
- }
- moc = null;
- mc = null;
- return strDiskID;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取CpuID
- /// </summary>
- /// <returns>CpuID</returns>
- public static string GetCpuID()
- {
- try
- {
- string strCpuID = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_Processor");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- strCpuID = mo.Properties["ProcessorId"].Value.ToString();
- }
- moc = null;
- mc = null;
- return strCpuID;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取操作系统类型
- /// </summary>
- /// <returns>操作系统类型</returns>
- public static string GetSystemType()
- {
- try
- {
- string strSystemType = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- strSystemType = mo["SystemType"].ToString();
- }
- moc = null;
- mc = null;
- return strSystemType;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取操作系统名称
- /// </summary>
- /// <returns>操作系统名称</returns>
- public static string GetSystemName()
- {
- try
- {
- string strSystemName = string.Empty;
- ManagementObjectSearcher mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT PartComponent FROM Win32_SystemOperatingSystem");
- foreach (ManagementObject mo in mos.Get())
- {
- strSystemName = mo["PartComponent"].ToString();
- }
- mos = new ManagementObjectSearcher("root\\CIMV2", "SELECT Caption FROM Win32_OperatingSystem");
- foreach (ManagementObject mo in mos.Get())
- {
- strSystemName = mo["Caption"].ToString();
- }
- return strSystemName;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取物理内存信息
- /// </summary>
- /// <returns>物理内存信息</returns>
- public static string GetTotalPhysicalMemory()
- {
- try
- {
- string strTotalPhysicalMemory = string.Empty;
- ManagementClass mc = new ManagementClass("Win32_ComputerSystem");
- ManagementObjectCollection moc = mc.GetInstances();
- foreach (ManagementObject mo in moc)
- {
- strTotalPhysicalMemory = mo["TotalPhysicalMemory"].ToString();
- }
- moc = null;
- mc = null;
- return strTotalPhysicalMemory;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取主板id
- /// </summary>
- /// <returns></returns>
- public static string GetMotherBoardID()
- {
- try
- {
- ManagementClass mc = new ManagementClass("Win32_BaseBoard");
- ManagementObjectCollection moc = mc.GetInstances();
- string strID = null;
- foreach (ManagementObject mo in moc)
- {
- strID = mo.Properties["SerialNumber"].Value.ToString();
- break;
- }
- return strID;
- }
- catch
- {
- return "unknown";
- }
- }
- /// <summary>
- /// 获取公用桌面路径
- public static string GetAllUsersDesktopFolderPath()
- {
- RegistryKey folders;
- folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders");
- string desktopPath = folders.GetValue("Common Desktop").ToString();
- return desktopPath;
- }
- /// <summary>
- /// 获取公用启动项路径
- /// </summary>
- public static string GetAllUsersStartupFolderPath()
- {
- RegistryKey folders;
- folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders");
- string Startup = folders.GetValue("Common Startup").ToString();
- return Startup;
- }
- private static RegistryKey OpenRegistryPath(RegistryKey root, string s)
- {
- s = s.Remove(0, 1) + @"/";
- while (s.IndexOf(@"/") != -1)
- {
- root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));
- s = s.Remove(0, s.IndexOf(@"/") + 1);
- }
- return root;
- }
- private void Test()
- {
- RegistryKey folders;
- folders = OpenRegistryPath(Registry.LocalMachine, @"/software/microsoft/windows/currentversion/explorer/shell folders");
- // Windows用户桌面路径
- string desktopPath = folders.GetValue("Common Desktop").ToString();
- // Windows用户字体目录路径
- string fontsPath = folders.GetValue("Fonts").ToString();
- // Windows用户网络邻居路径
- string nethoodPath = folders.GetValue("Nethood").ToString();
- // Windows用户我的文档路径
- string personalPath = folders.GetValue("Personal").ToString();
- // Windows用户开始菜单程序路径
- string programsPath = folders.GetValue("Programs").ToString();
- // Windows用户存放用户最近访问文档快捷方式的目录路径
- string recentPath = folders.GetValue("Recent").ToString();
- // Windows用户发送到目录路径
- string sendtoPath = folders.GetValue("Sendto").ToString();
- // Windows用户开始菜单目录路径
- string startmenuPath = folders.GetValue("Startmenu").ToString();
- // Windows用户开始菜单启动项目录路径
- string startupPath = folders.GetValue("Startup").ToString();
- // Windows用户收藏夹目录路径
- string favoritesPath = folders.GetValue("Favorites").ToString();
- // Windows用户网页历史目录路径
- string historyPath = folders.GetValue("History").ToString();
- // Windows用户Cookies目录路径
- string cookiesPath = folders.GetValue("Cookies").ToString();
- // Windows用户Cache目录路径
- string cachePath = folders.GetValue("Cache").ToString();
- // Windows用户应用程式数据目录路径
- string appdataPath = folders.GetValue("Appdata").ToString();
- // Windows用户打印目录路径
- string printhoodPath = folders.GetValue("Printhood").ToString();
- }</span>
来自小勇.NET博客:http://blog.csdn.net/xiaoyong_net
版权声明:本文为云勇原创文章,转载请注明来源于云勇博客
c#中如何获取本机MAC地址、IP地址、硬盘ID、CPU序列号等系统信息的更多相关文章
- js获取本机的网络IP地址
JavaScript是一门脚本语言,是不能操作文件,读取本地信息的,所以想要获取IP,还需要借助后端技术.方法如下: //获取本机的网络ip地址 function jsonpCallback(res) ...
- LabVIEW 获取本机多个ip地址
图 1 网上见了好多设置的,都没讲清楚,在这里整理一下本机ip地址的获取问题.关键在"字符串向ip地址转换"函数的设置上面,见下图2,选择多输出就能获取本机的多个ip地址,若不 ...
- C# 获取本机的所有ip地址,并过滤内网ip
private void Initialization_Load(object sender, EventArgs e) { cboxip.Items.Add("请选择IP地址") ...
- c#中如何获取本机用户名、MAC地址、IP地址、硬盘ID、CPU序列号、系统名称、物理内存
我们在利用C#开发桌面程序(Winform)程序的时候, 经常需要获取一些跟系统相关的信息, 以下这些代码获取能有些用处. c#中如何获取本机用户名.MAC地址.IP地址.硬盘ID.CPU序列号.系统 ...
- java获取本机名称、IP、MAC地址和网卡名称
java获取本机名称.IP.MAC地址和网卡名称 摘自:https://blog.csdn.net/Dai_Haijiao/article/details/80364370 2018年05月18日 1 ...
- 脚本_获取本机 MAC 地址
#!bin/bash#作者:liusingbon#功能:获取本机 MAC 地址ip a s |awk 'BEGIN{print "本机 MAC 地址信息如下:"}/^[0-9]/{ ...
- js获取本机mac地址,IP地址,计算机名
<!DOCTYPE HTML> <html> <head> <title>js获取本机mac地址,IP地址,计算机名</title> < ...
- windows获取本机MAC地址并写入文件的bat
windows获取本机MAC地址并写入文件的bat MAC(Media Access Control)地址,或称为 MAC地址.硬件地址,用来定义网络设备的位置. bat代码例如以下: @echo o ...
- Java获取本机MAC地址[转]
原文地址:https://www.cnblogs.com/hxsyl/p/3422191.html Java获取本机MAC地址 为什么写这个呢?因为前几天看见网上有采用windows命令获取局域网 ...
随机推荐
- AOJ2025 Eight Princes
我们查看更一般的情况,设人数为m 则n < m * 2无解 然后n为奇数的情况: 我们把一个人和一个空格打包,于是剩下m个"人"和n - m个空格,随便排列这些"人 ...
- POJ 1008 简单模拟题
e.... 虽然这是一道灰常简单的模拟题.但是米做的时候没有读懂第二个日历的计时方法.然后捏.敲完之后华丽的WA了进一个点.坑点就在一年的最后一天你是该输出本年的.e ...但是我好想并没有..看di ...
- 北邮新生排位赛2解题报告d-e
<> 427. 学姐逗学弟 时间限制 3000 ms 内存限制 131072 KB 题目描述 学弟们来了之后,学姐每天都非常高兴的和学弟一起玩耍.这一天,学姐想出了这样一个游戏,她画了一棵 ...
- AnsiStartsStr 和 空字符串
function AnsiStartsStr(const ASubText, AText: string): Boolean; begin Result := AnsiSameStr(ASubText ...
- selenium(一)简介,安装,配置,测试。
简介: Selenium也是一个用于Web应用程序测试的工具.Selenium测试直接运行在浏览器中,就像真正的用户在操作一样.支持的浏览器包括IE.Mozilla Firefox.Mozilla S ...
- docker(一)安装和必要的配置。
Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器中,然后发布到任何流行的 Linux 机器上,也可以实现虚拟化.容器是完全使用沙箱机制,相互之间不会有任何 ...
- 元素大小-偏移量(offset)客户区大小(client)滚动大小(scroll)
一.偏移量---offset 1.定位父级 在理解偏移大小之前,首先要理解offsetParent.人们并没有把offsetParent翻译为偏移父级,而是翻译成定位父级,很大原因是offsetPar ...
- http请求报头
客户请求的处理:Http请求报头 创建高效servlet的关键之一,就是要了解如何操纵超文本传输协议(HypeText TransferProtocol, HTTP). HTTP请求报头不同于前一章的 ...
- 深入理解Linux网络技术内幕——网络设备初始化
概述 内核的初始化过程过程中,与网络相关的工作如下所示: 内核引导时执行start_kernel,start_kernel结束之前会调用rest_init,rest_init初始化内核线 ...
- Linux:查看进程运行时间
查看进程运行时间 应用ps命令,加选项-Ao,加参数,最后过滤. ps -Ao pid,tty,user,stime,etime,comm,args| grep firefox pid:进程ID tt ...