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;
            }
        }
相关推荐
金銀銅鐵9 小时前
为什么枚举类中可以定义抽象方法
java·后端·ai编程
文丑颜不良啊10 小时前
LeetCode1941~1960题目解析
java·leetcode
txxzjmzlh11 小时前
SpringBoot 统⼀功能处理
java·spring boot·后端
nice_lcj52012 小时前
Java Lambda 表达式入门:怎么写、怎么用、常用方法有哪些
java·开发语言·后端·面试
码农小河6613 小时前
基于SSM+JSP+MySQL的在线医疗服务系统的设计与实现
java·开发语言·mysql
SL_staff14 小时前
从配置失效到逻辑复用:JVS-Logic 如何构建可治理的业务编排中枢
java·spring·产品
特立独行的猫A14 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
文丑颜不良啊15 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊15 小时前
LeetCode2001~2020题目解析
java·leetcode
用户37215742613515 小时前
Java 批量提取 Word 文档中的图片并保存到本地
java