C# 获取MAC地址

通过CMD命令进行获取

使用CMD命令这将面临语言编码问题,可以通过命令让系统默认采用美国英文来显示:

chcp 437
MacAddress = MacAddressHelper.GetMacByIpConfig() ?? MacAddressHelper.GetMacByWmi().FirstOrDefault() ?? "unknown"; //通过命令让系统默认采用美国英文来显示:
 ///<summary>
        /// 根据截取ipconfig /all命令的输出流获取网卡Mac,支持不同语言编码
        ///</summary>
        ///<returns></returns>
        public static string GetMacByIpConfig()
        {
            List<string> macs = new List<string>();

            var runCmd = Cmd.RunCmd("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();
        }

 

posted @ 2020-05-02 13:19  caiji001  阅读(442)  评论(0)    收藏  举报