.net core web 应用程序获取cpu序列号

.net web 应用程序获取cpu序列号

问题描述

我最近遇到一个需求,需要在 .Net Core 5.0 Web 应用程序中获取当前服务器的CPU序列号。 我的操作系统是windows。
我参考网上关于 .net 获取cpu序列号的方法时,查到的方法大多是使用【System.Management】如:
image-20230505160342132

程序运行报错:

System.Management currently is only supported for Windows desktop applications

看来【System.Management】库只支持windows桌面应用程序,如WPF、Windows Form应用程序。不再支持.Net Web 程序。需要另想解决办法。

解决方案

解决方案是调用cmd控制台来获取CPU信息。

cmd控制台中输入以下命令行,就能获取到CPU序列号:

wmic CPU get ProcessorID

image-20230505161329943

c#代码如下:

		private static string CMDPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + "\\cmd.exe";

        public static void RunCMDCommand(string Command, out string OutPut)
        {
            using (var pc = new System.Diagnostics.Process())
            {
                Command = Command.Trim().TrimEnd('&') + "&exit";
                pc.StartInfo.FileName = CMDPath;
                pc.StartInfo.CreateNoWindow = true;
                pc.StartInfo.RedirectStandardError = true;
                pc.StartInfo.RedirectStandardInput = true;
                pc.StartInfo.RedirectStandardOutput = true;
                pc.StartInfo.UseShellExecute = false;
                pc.Start();
                pc.StandardInput.WriteLine(Command);
                pc.StandardInput.AutoFlush = true;
                OutPut = pc.StandardOutput.ReadToEnd();
                int P = OutPut.IndexOf(Command) + Command.Length;
                OutPut = OutPut.Substring(P, OutPut.Length - P - 3);
                pc.WaitForExit();
                pc.Close();
            }
        }

        /// <summary>
        /// 获取cpu序列号
        /// </summary>
        /// <returns></returns>
        public static string GetCpuId()
        {
            RunCMDCommand("wmic CPU get ProcessorID", out string processId);
            //市面上的电脑一般只安装一块CPU,我们直接取值即可
            processId = processId.Replace("ProcessorId", "").Replace("\n", "").Trim();
            return processId;
        }

猜你喜欢

转载自blog.csdn.net/guigenyi/article/details/130509607
今日推荐