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");
        }
相关推荐
荣世蓥8 分钟前
6.C基础_输入输出函数
c语言·开发语言
程序员不想YY啊11 分钟前
【保姆级讲解C语言中的运算符的优先级!】
android·c语言·开发语言
格林威23 分钟前
Baumer工业相机堡盟工业相机如何通过BGAPISDK建立线程监控相机的温度(C#)
开发语言·人工智能·数码相机·计算机视觉·c#
范范082526 分钟前
Scala基础入门:从零开始学习Scala编程
开发语言·学习·scala
宏笋27 分钟前
Qt:自定义钟表组件
开发语言·qt
酷爱码29 分钟前
Go语言编程大全,web微服务数据库十大专题精讲
开发语言
ProMan_XY32 分钟前
干货-并发编程提高——线程的唤醒(七)
java·开发语言
Bruce_Ling1 小时前
基于VScode和C++实现Protobuf数据格式的通信
开发语言·c++·vscode·算法
宋发元1 小时前
使用Go语言绘制水平柱状图教程
开发语言·后端·golang
susan花雨1 小时前
C# 判断电脑是否联网
c#