c#获取本机的MAC地址(附源码)

在前一次的项目中,突然用到了这个获取本机的MAC地址,然后就研究了一下,记录下来,防止以后再用到,

使用winfrom做的,界面一个button,一个textBox,点了button以后给textBox赋值显示mac地址

附上源码

cs 复制代码
 private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                string macAddress = GetMacAddress();
                if (!string.IsNullOrEmpty(macAddress))
                {
                    textBox1.Text = macAddress;
                }
                else
                {
                    MessageBox.Show("未能获取到MAC地址。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取MAC地址时出现错误:{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private string GetMacAddress()
        {
            try
            {
                string macAddress = string.Empty;
                foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
                {
                    /// 仅考虑以太网的网络接口
                    if (nic.NetworkInterfaceType == NetworkInterfaceType.Ethernet && nic.OperationalStatus == OperationalStatus.Up)
                    {
                        // 获取网络接口的MAC地址
                        macAddress = nic.GetPhysicalAddress().ToString();
                        // 将连续的十六进制数格式化为带冒号分隔符的形式
                        macAddress = FormatMacAddress(macAddress);
                        if (!string.IsNullOrEmpty(macAddress))
                            break;
                    }
                }
                return macAddress;
            }
            catch (UnauthorizedAccessException)
            {
                throw new Exception("没有足够的权限来访问网络接口信息,请以管理员身份运行程序。");
            }
            catch (Exception ex)
            {
                throw new Exception($"获取MAC地址时出现错误:{ex.Message}");
            }
        }
        // 使用正则表达式将连续的十六进制数格式化为带冒号分隔符的形式
        private string FormatMacAddress(string macAddress)
        {
            
            return Regex.Replace(macAddress, @"(.{2})(.{2})(.{2})(.{2})(.{2})(.{2})", "$1:$2:$3:$4:$5:$6");
        }
相关推荐
wdfk_prog8 小时前
[Linux]学习笔记系列 -- [kernel]kallsyms
linux·笔记·学习
Elnaij8 小时前
从C++开始的编程生活(12)——vector简单介绍和迭代器
开发语言·c++
饼干,9 小时前
第23天python内容
开发语言·python
!chen9 小时前
CPP 学习笔记 语法总结
c++·笔记·学习
数学难9 小时前
Java面试题2:Java线程池原理
java·开发语言
Charles_go9 小时前
C#8、有哪些访问修饰符
java·前端·c#
咸鱼求放生9 小时前
Java 8 Stream API
java·开发语言
盒马盒马9 小时前
Rust:Trait 抽象接口 & 特征约束
开发语言·rust
现在,此刻9 小时前
李沐深度学习笔记D3-线性回归
笔记·深度学习·线性回归
天使街23号9 小时前
go-dongle v1.2.0 发布,新增 SM2 非对称椭圆曲线加密算法支持
开发语言·后端·golang