C#中使用ManagementClass获取本机信息

C#提供 ManagementClass来对机器的信息进行管理,可以通过设定不同的管理类来获得机器的基本信息。下面给出了一些基本的信息的获取方法,包括获取CPU数目,cpu频率,内存大小,硬盘大小。

 

private void GetLocalInfo()
        {
            string cpuCount;
            string hdSize;
            string memorysize;
           
            //得到CPU信息
            ManagementClass mcpu = new ManagementClass("Win32_Processor");
            ManagementObjectCollection mncpu = mcpu.GetInstances();
            cpuCount = mncpu.Count.ToString();
            string[] cpuHz = new string[mncpu.Count];
            int count = 0;
            ManagementObjectSearcher MySearcher = new ManagementObjectSearcher("SELECT * FROM Win32_Processor");
            foreach (ManagementObject MyObject in MySearcher.Get())
            {
                cpuHz[count] = MyObject.Properties["CurrentClockSpeed"].Value.ToString();
                count++;
            }
            mncpu.Dispose();
            mcpu.Dispose();

            //得到硬盘信息
            ManagementClass mcHD = new ManagementClass("Win32_DiskDrive");
            ManagementObjectCollection moHD = mcHD.GetInstances();

            foreach (ManagementObject tempob in moHD)
            {
                hdSize = tempob.Properties["Size"].Value.ToString();
            }
            moHD.Dispose();
            mcHD.Dispose();

            //得到内存信息
            ManagementClass mcMemory = new ManagementClass("Win32_OperatingSystem");
            ManagementObjectCollection mocMemory = mcMemory.GetInstances();

            double sizeall = 0;
            foreach (ManagementObject mo in mocMemory)
            {
                if (mo.Properties["TotalVisibleMemorySize"].Value != null)
                {
                    sizeall += double.Parse(mo.Properties["TotalVisibleMemorySize"].Value.ToString());
                }
            }
            memorysize = sizeall.ToString();
            mocMemory.Dispose();
            mcMemory.Dispose();

}
//获取mac地址

public static ArrayList GetMacAddress()
        {
            ManagementClass class1 = new ManagementClass("Win32_NetworkAdapterConfiguration");
            ManagementObjectCollection collection1 = class1.GetInstances();
            ArrayList list1 = new ArrayList();
            using (ManagementObjectCollection.ManagementObjectEnumerator enumerator1 = collection1.GetEnumerator())
            {
                while (enumerator1.MoveNext())
                {
                    ManagementObject obj1 = enumerator1.get_Current();
                    if ((bool) obj1.get_Item("IPEnabled"))
                    {
                        list1.Add(obj1.get_Item("MacAddress").ToString().Replace(":", ""));
                    }
                    obj1.Dispose();
                }
            }
            return list1;
        }

//ping网络状态

[DllImport("wininet.dll")]
        private static extern bool InternetGetConnectedState(int Description, int ReservedValue);
        public static bool IsConnectedToInternet()
        {
            int num1 = 0;
            return InternetGetConnectedState(num1, 0);
        }

 

 

using System;

using System.Collections;

using System.Diagnostics;

using System.Management;

using System.Net;

using System.DirectoryServices;

using System.Runtime.InteropServices;

using System.Text.RegularExpressions;

获得本机的MAC地址

        public static string GetLocalMac()

        {

            string strMac = string.Empty;

            ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");

            ManagementObjectCollection moc = mc.GetInstances();

            foreach(ManagementObject mo in moc)

            {

                if ((bool)mo["IPEnabled"] == true)

                    strMac += mo["MacAddress"].ToString() ;

 

            }

            return strMac.ToUpper();

        }

获得远程计算机的MAC地址

方法一:使用API,利用ARP协议,只能获得同网段计算机的MAC

        [DllImport("Iphlpapi.dll")]

        private static extern int SendARP(Int32 dest,Int32 host,ref Int64 mac,ref Int32 length);

        [DllImport("Ws2_32.dll")]

        private static extern Int32 inet_addr(string ip);

        public static string GetRemoteMac(string clientIP)

        {

            string ip = clientIP;

            if ( ip == "127.0.0.1")

                ip = GetLocalIP()[0];

            Int32 ldest=inet_addr(ip);

            Int64 macinfo=new Int64();

            Int32 len=6;

            try

            {

                SendARP(ldest,0,ref macinfo,ref len);

            }

            catch

            {

                return "";

            }

            string originalMACAddress = Convert.ToString(macinfo,16);

            if (originalMACAddress.Length<12)

            {

                originalMACAddress = originalMACAddress.PadLeft(12,'0');

            }

            string macAddress;

            if(originalMACAddress!="0000" && originalMACAddress.Length==12)

            {

                string mac1,mac2,mac3,mac4,mac5,mac6;

                mac1=originalMACAddress.Substring(10,2);

                mac2=originalMACAddress.Substring(8,2);

                mac3=originalMACAddress.Substring(6,2);

                mac4=originalMACAddress.Substring(4,2);

                mac5=originalMACAddress.Substring(2,2);

                mac6=originalMACAddress.Substring(0,2);

                macAddress=mac1+"-"+mac2+"-"+mac3+"-"+mac4+"-"+mac5+"-"+mac6;

            }

            else

            {

                macAddress="";

            }

            return macAddress.ToUpper();

        }

 

方法二:使用windows的命令nbtstat

 

        public static string GetRemoteMacByNetBIOS(string clientIP)

        {

            string ip = clientIP;

            if ( ip == "127.0.0.1")

                ip = GetLocalIP()[0];

            string dirResults="";

            ProcessStartInfo psi = new ProcessStartInfo();

            Process proc = new Process();

            psi.FileName = "nbtstat.exe";

            //psi.RedirectStandardInput = false;

            psi.RedirectStandardOutput = true;psi.RedirectStandardError=true;

            psi.Arguments = "-A " + ip;

            psi.UseShellExecute = false;

            proc = Process.Start(psi);

            dirResults = proc.StandardOutput.ReadToEnd();

            string error = proc.StandardError.ReadToEnd();

            proc.WaitForExit();

            dirResults=dirResults.Replace("\r","").Replace("\n","").Replace("\t","");

 

            Regex reg=new Regex("Mac[ ]{0,}Address[ ]{0,}=[ ]{0,}(?((.)*?))__MAC",RegexOptions.IgnoreCase|RegexOptions.Compiled);

            Match mc=reg.Match(dirResults+"__MAC");

 

            if(mc.Success)

            {

                return mc.Groups["key"].Value.ToUpper();

            }

            else

            {                   

               return "";

            }

        }

使用此方法需要足够的操作系统的权限。在Web中,可以将ASP.net用户加入管理员组。

对于上面两个地方都用到的GetLocalIP是一个获取本机IP的方法:

        public static string[] GetLocalIP()

        {

            string hostName = Dns.GetHostName();

            IPHostEntry ipEntry=Dns.GetHostByName(hostName);

            IPAddress[] arr=ipEntry.AddressList;

            string[] result = new string[arr.Length];

            for(int i=0;i            {

                result[i] = arr[i].ToString();  

            }

            return result;

        } 

获得局域网内计算机的列表

方法一:使用逐个IP地址扫描的方式

利用多线程来对每个IP逐个扫描。

ComputerAddressInfo cai = new ComputerAddressInfo("192.168.1",42,53);

Thread thScan = new Thread(new ThreadStart(cai.ScanComputers));

thScan.Start();

//...

    public class ComputerAddressInfo

    {

 

        private int startIP = 0;

        private int endIP = 0;

        private string ipPrefix = "";

        private ArrayList computerList = null;

  

        public ComputerAddressInfo(string ipPrefix,int startIP,int endIP)

        {

            this.startIP = startIP;

            this.endIP = endIP;

            this.ipPrefix = ipPrefix;

            computerList = new ArrayList();

        }

 

 

 

 

 

        public void ScanComputers()

        {

            for(int i=startIP;i<=endIP;i++)

            {

                string scanIP = ipPrefix +"."+i.ToString();

                IPAddress myScanIP = IPAddress.Parse(scanIP);

                IPHostEntry myScanHost = null;

                string[] arr = new string[2];

                try

                {

                    myScanHost = Dns.GetHostByAddress(myScanIP);

                }

                catch

                {

                    continue;

                }

                if (myScanHost != null)

                {

                    arr[0] = myScanHost.HostName;

                    arr[1] = scanIP;

                    computerList.Add(arr);

                }

            }

        }

    }

 

此方法速度比较慢。

方法二:使用Active Directory

        public static ArrayList GetComputerList() 

       

            ArrayList list = new ArrayList();

            //or use "WinNT://your_domain_name" 

            DirectoryEntry root = new DirectoryEntry("WinNT:");

            DirectoryEntries domains = root.Children; 

            domains.SchemaFilter.Add("domain"); 

            foreach (DirectoryEntry domain in domains) 

            {   

                DirectoryEntries computers = domain.Children; 

                computers.SchemaFilter.Add("computer"); 

                foreach (DirectoryEntry computer in computers) 

               

                    object[] arr = new string[3];

                    IPHostEntry iphe = null;

                    try

                    {

                        iphe = Dns.GetHostByName(computer.Name);

                    }

                    catch

                    {

                        continue;

                    }

                    arr[0] = domain.Name;

                    arr[1] = computer.Name;

                    if ( iphe != null && iphe.AddressList.Length >0 )

                    {

                        for ( int i=0;i                            arr[2] += iphe.AddressList[i].ToString()+",";

                        arr[2] = arr[2].ToString().Remove(arr[2].ToString().Length-1,1);

                    }

                    else

                        arr[2] = "";

                    list.Add(arr);

               

           

            return list;

       

 

此方法速度也比较慢。

后记

上面两个获得局域网内的计算机列表的方法都很费时,目前还没有找到更好的办法。

 

点点点

 

C# 硬件码 获取电脑配置信息

class ActiveX
    {
        public static string hardCode()
        {
            string temp = CpuID() + "_" + DiskID() + "_" + TotalPhysicalMemory() + "_" + SystemType() + "_" + MacAddress() ;
            temp = temp.ToUpper();
            string result = Md5Create.getMd5Hash(temp);
            return result;
        }

        private static string CpuID()
        {
            string cpuID = "";

            ManagementClass mc = null;
            ManagementObjectCollection moc = null;
            try
            {
                mc = new ManagementClass("Win32_Processor");
                moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    cpuID = mo.Properties["ProcessorId"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                LogWrite.Write("ActiveX.CpuID:"+ex.Message);
                cpuID = "unknow";
            }
            finally
            {
                moc = null;
                mc = null;
            }
            return cpuID;
        }

        private static string MacAddress()
        {
            string macAddress = "";

            ManagementClass mc = null;
            ManagementObjectCollection moc = null;
            try
            {
                mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        macAddress = mo["MacAddress"].ToString();
                        return macAddress;
                    }
                }
            }
            catch (Exception ex)
            {
                LogWrite.Write("ActiveX.MacAddress:" + ex.Message);
                macAddress = "unknow";
            }
            finally
            {
                moc = null;
                mc = null;
            }

            return macAddress;
        }

        private static string DiskID()
        {
            string diskID = "";

            ManagementClass mc = null;
            ManagementObjectCollection moc = null;
            try
            {
                mc = new ManagementClass("Win32_DiskDrive");
                moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    diskID = mo.Properties["Model"].Value.ToString();
                }
            }
            catch (Exception ex)
            {
                LogWrite.Write("ActiveX.DiskID:" + ex.Message);
                diskID = "unknow";
            }
            finally
            {
                moc = null;
                mc = null;
            }
            return diskID;
        }

        private static string SystemType()
        {
            string systemType = "";

            ManagementClass mc = null;
            ManagementObjectCollection moc = null;
            try
            {
                mc = new ManagementClass("Win32_ComputerSystem");
                moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    systemType = mo["SystemType"].ToString();
                }
            }
            catch (Exception ex)
            {
                LogWrite.Write("ActiveX.SystemType:" + ex.Message);
                systemType = "unknow";
            }
            finally
            {
                moc = null;
                mc = null;
            }

            return systemType;
        }

        private static string TotalPhysicalMemory()
        {
            string totalPhysicalMemory = "";

            ManagementClass mc = null;
            ManagementObjectCollection moc = null;
            try
            {
                mc = new ManagementClass("Win32_ComputerSystem");
                moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    totalPhysicalMemory = mo["TotalPhysicalMemory"].ToString();
                }
            }
            catch (Exception ex)
            {
                LogWrite.Write("ActiveX.TotalPhysicalMemory:" + ex.Message);
                totalPhysicalMemory = "unknow";
            }
            finally
            {
                moc = null;
                mc = null;
            }

            return totalPhysicalMemory;
        }
    }

-------------------------------------------------

 

需要强调的是客户机器的硬件信息获取方式是有很多种选择的. 这里我们选择最放心的两个硬件: CUP的序列号和硬盘的卷标号. 好了, 下面您就可以一步一步制作一款软件注册机了. 

 

 

步骤一: 获得CUP序列号和硬盘序列号的实现代码如下:



public string getCpu()
{
string strCpu = null;
ManagementClass myCpu
= new ManagementClass("win32_Processor");
ManagementObjectCollection myCpuConnection
= myCpu.GetInstances();
foreach( ManagementObject myObject in myCpuConnection)
{
strCpu
= myObject.Properties["Processorid"].Value.ToString();
break;
}
return strCpu;
}

 



public string GetDiskVolumeSerialNumber()
{
ManagementClass mc
= new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObject disk
= new ManagementObject("win32_logicaldisk.deviceid=\"d:\"");
disk.Get();
return disk.GetPropertyValue("VolumeSerialNumber").ToString();
}

 

 

步骤二: 收集硬件信息生成机器码, 代码如下: 



private void button1_Click(object sender, EventArgs e)
{
label2.Text
= getCpu() + GetDiskVolumeSerialNumber();//获得24位Cpu和硬盘序列号
string[] strid = new string[24];//
for (int i = 0; i < 24; i++)//把字符赋给数组
{
strid[i]
= label2.Text.Substring(i, 1);
}
label2.Text
= "";
Random rdid
= new Random();
for (int i = 0; i < 24; i++)//从数组随机抽取24个字符组成新的字符生成机器三
{
label2.Text
+= strid[rdid.Next(0, 24)];
}
}

 

 

步骤三: 使用机器码生成软件注册码, 代码如下:


public int[] intCode = new int[127];//用于存密钥
public void setIntCode()//给数组赋值个小于10的随机数
{
Random ra
= new Random();
for (int i = 1; i < intCode.Length;i++ )
{
intCode[i]
= ra.Next(0, 9);
}
}
public int[] intNumber = new int[25];//用于存机器码的Ascii值
public char[] Charcode = new char[25];//存储机器码字

//生成注册码
private void button2_Click(object sender, EventArgs e)
{
if (label2.Text != "")
{
//把机器码存入数组中
setIntCode();//初始化127位数组
for (int i = 1; i < Charcode.Length; i++)//把机器码存入数组中
{
Charcode[i]
= Convert.ToChar(label2.Text.Substring(i - 1, 1));
}
//
for (int j = 1; j < intNumber.Length; j++)//把字符的ASCII值存入一个整数组中。
{
intNumber[j]
= intCode[Convert.ToInt32(Charcode[j])] + Convert.ToInt32(Charcode[j]);

}
string strAsciiName = null;//用于存储机器码
for (int j = 1; j < intNumber.Length; j++)
{
//MessageBox.Show((Convert.ToChar(intNumber[j])).ToString());
if (intNumber[j] >= 48 && intNumber[j] <= 57)//判断字符ASCII值是否0-9之间
{
strAsciiName
+= Convert.ToChar(intNumber[j]).ToString();
}
else if (intNumber[j] >= 65 && intNumber[j] <= 90)//判断字符ASCII值是否A-Z之间
{
strAsciiName
+= Convert.ToChar(intNumber[j]).ToString();
}
else if (intNumber[j] >= 97 && intNumber[j] <= 122)//判断字符ASCII值是否a-z之间
{
strAsciiName
+= Convert.ToChar(intNumber[j]).ToString();
}
else//判断字符ASCII值不在以上范围内
{
if (intNumber[j] > 122)//判断字符ASCII值是否大于z
{ strAsciiName += Convert.ToChar(intNumber[j] - 10).ToString(); }
else
{
strAsciiName
+= Convert.ToChar(intNumber[j] - 9).ToString();
}

}
label3.Text
= strAsciiName;//得到注册码

}
}
else
{ MessageBox.Show(
"请选生成机器码","注册提示"); }
}

 

 

    步骤四: 用户输入注册码注册软件, 演示代码如下:

 


private void btnRegist_Click(object sender, EventArgs e)
{
if (label3.Text != "")
{
if (textBox1.Text.TrimEnd().Equals(label3.Text.TrimEnd()))
{

Microsoft.Win32.RegistryKey retkey
= Microsoft.Win32.Registry.CurrentUser.
OpenSubKey(
"software", true).CreateSubKey("ZHY").CreateSubKey("ZHY.INI").
CreateSubKey(textBox1.Text.TrimEnd());
retkey.SetValue(
"UserName", "MySoft");
MessageBox.Show(
"注册成功");
}
else
{
MessageBox.Show(
"注册码输入错误");

}

}
else { MessageBox.Show("请生成注册码","注册提示"); }

}

 

posted @ 2011-11-08 11:30  火腿骑士  阅读(3678)  评论(0编辑  收藏  举报