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");
        }
相关推荐
代码or搬砖25 分钟前
Java集合-Set讲解
java·开发语言
艾上编程26 分钟前
第三章——爬虫工具场景之Python爬虫实战:学术文献摘要爬取,助力科研高效进行
开发语言·爬虫·python
d111111111d28 分钟前
在STM32函数指针是什么,怎么使用还有典型应用场景。
笔记·stm32·单片机·嵌入式硬件·学习·算法
明洞日记33 分钟前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
静小谢42 分钟前
前后台一起部署,vite配置笔记base\build
前端·javascript·笔记
jllllyuz1 小时前
matlab使用B样条进行曲线曲面拟合
开发语言·matlab
ask_baidu1 小时前
Doris笔记
android·笔记
ku_code_ku2 小时前
python bert_score使用本地模型的方法
开发语言·python·bert
小马哥编程2 小时前
【软考架构】滑动窗口限流算法的原理是什么?
java·开发语言·架构
云栖梦泽2 小时前
鸿蒙数据持久化实战:构建本地存储与云同步系统
开发语言·鸿蒙系统