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");
        }
相关推荐
百锦再12 分钟前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame
Anson Jiang13 分钟前
浏览器标签页管理:使用chrome.tabs API实现新建、切换、抓取内容——Chrome插件开发从入门到精通系列教程06
开发语言·前端·javascript·chrome·ecmascript·chrome devtools·chrome插件
唐青枫17 分钟前
从入门到进阶:C#.NET Stopwatch 计时与性能测量全攻略
c#·.net
会开花的二叉树22 分钟前
继承与组合:C++面向对象的核心
java·开发语言·c++
长河2 小时前
Java开发者LLM实战——LangChain4j最新版教学知识库实战
java·开发语言
Cyan_RA92 小时前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
再见晴天*_*5 小时前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08277 小时前
Qt程序单独运行报错问题
开发语言·qt
Hello_Embed7 小时前
STM32HAL 快速入门(二十):UART 中断改进 —— 环形缓冲区解决数据丢失
笔记·stm32·单片机·学习·嵌入式软件
咸甜适中7 小时前
rust语言 (1.88) 学习笔记:客户端和服务器端同在一个项目中
笔记·学习·rust