C# 获取当前电脑的mac地址

C# 获取当前电脑的mac地址

不多说,上代码。一个方法GetMacByIpConfig

csharp 复制代码
        public string GetMacByIpConfig()
        {
            List<string> macs = new List<string>();
            var runCmd = ExecuteInCmd("chcp 437&&ipconfig/all");
            foreach (var line in runCmd.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()))
            {
                if (!string.IsNullOrEmpty(line))
                {
                    if (line.StartsWith("Physical Address"))
                    {
                        macs.Add(line.Substring(36));
                    }
                    else if (line.StartsWith("DNS Servers") && line.Length > 36 && line.Substring(36).Contains("::"))
                    {
                        macs.Clear();
                    }
                    else if (macs.Count > 0 && line.StartsWith("NetBIOS") && line.Contains("Enabled"))
                    {
                        return macs.Last();
                    }
                }
            }
            return macs.FirstOrDefault();
        }

上面方法需要调用某一个方法

csharp 复制代码
        public static string ExecuteInCmd(string cmdline)
        {
            using (var process = new Process())
            {
                process.StartInfo.FileName = "cmd.exe";
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.RedirectStandardInput = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError = true;
                process.StartInfo.CreateNoWindow = true;

                process.Start();
                process.StandardInput.AutoFlush = true;
                process.StandardInput.WriteLine(cmdline + "&exit");

                //获取cmd窗口的输出信息  
                string output = process.StandardOutput.ReadToEnd();

                process.WaitForExit();
                process.Close();

                return output;
            }
        }
相关推荐
北执南念6 分钟前
基于 Spring 的策略模式框架,用于根据不同的类的标识获取对应的处理器实例
java·spring·策略模式
王道长服务器 | 亚马逊云10 分钟前
一个迁移案例:从传统 IDC 到 AWS 的真实对比
java·spring boot·git·云计算·github·dubbo·aws
华仔啊14 分钟前
为什么 keySet() 是 HashMap 遍历的雷区?90% 的人踩过
java·后端
9号达人27 分钟前
Java 13 新特性详解与实践
java·后端·面试
橙序员小站33 分钟前
搞定系统设计题:如何设计一个支付系统?
java·后端·面试
嘟嘟可在哪里。1 小时前
IntelliJ IDEA git凭据帮助程序
java·git·intellij-idea
岁忧1 小时前
(LeetCode 每日一题) 3541. 找到频率最高的元音和辅音 (哈希表)
java·c++·算法·leetcode·go·散列表
_extraordinary_1 小时前
Java 多线程进阶(四)-- 锁策略,CAS,synchronized的原理,JUC当中常见的类
java·开发语言
纪元A梦2 小时前
贪心算法应用:信用评分分箱问题详解
java·算法·贪心算法
大飞pkz2 小时前
【设计模式】题目小练2
开发语言·设计模式·c#·题目小练