C#获取机器码的方法详解(机器名,CPU编号,硬盘编号,网卡mac等)

本文实例讲述了C#获取机器码的方法。分享给大家供大家参考,具体如下:

using System.Runtime.InteropServices;
using System.Management;
using System;
public class HardwareInfo
{
  //取机器名
  public string GetHostName()
  {
  return System.Net.Dns.GetHostName();
  }
  //取CPU编号
  public String GetCpuID()
  {
    try
    {
      ManagementClass mc = new ManagementClass("Win32_Processor");
      ManagementObjectCollection moc = mc.GetInstances();
      String strCpuID = null ;
      foreach( ManagementObject mo in moc )
      {
        strCpuID = mo.Properties["ProcessorId"].Value.ToString();
        break;
      }
      return strCpuID;
    }
    catch
    {
      return "";
    }
  }//end method
//取第一块硬盘编号
  public String GetHardDiskID()
  {
    try
    {
      ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");
      String strHardDiskID = null ;
      foreach(ManagementObject mo in searcher.Get())
      {
        strHardDiskID = mo["SerialNumber"].ToString().Trim();
        break;
      }
      return strHardDiskID ;
    }
    catch
    {
      return "";
    }
  }//end
public enum NCBCONST
{
  NCBNAMSZ =16, /* absolute length of a net name */
  MAX_LANA =254, /* lana's in range 0 to MAX_LANA inclusive */
  NCBENUM =0x37, /* NCB ENUMERATE LANA NUMBERS */
  NRC_GOODRET =0x00, /* good return */
  NCBRESET =0x32, /* NCB RESET */
  NCBASTAT =0x33, /* NCB ADAPTER STATUS */
  NUM_NAMEBUF =30, /* Number of NAME's BUFFER */
}
  [StructLayout(LayoutKind.Sequential)]
  public struct ADAPTER_STATUS
  {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=6)]
    public byte[] adapter_address;
    public byte rev_major;
    public byte reserved0;
    public byte adapter_type;
    public byte rev_minor;
    public ushort duration;
    public ushort frmr_recv;
    public ushort frmr_xmit;
    public ushort iframe_recv_err;
    public ushort xmit_aborts;
    public uint xmit_success;
    public uint recv_success;
    public ushort iframe_xmit_err;
    public ushort recv_buff_unavail;
    public ushort t1_timeouts;
    public ushort ti_timeouts;
    public uint reserved1;
    public ushort free_ncbs;
    public ushort max_cfg_ncbs;
    public ushort max_ncbs;
    public ushort xmit_buf_unavail;
    public ushort max_dgram_size;
    public ushort pending_sess;
    public ushort max_cfg_sess;
    public ushort max_sess;
    public ushort max_sess_pkt_size;
    public ushort name_count;
  }
  [StructLayout(LayoutKind.Sequential)]
  public struct NAME_BUFFER
  {
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
    public byte[] name;
    public byte name_num;
    public byte name_flags;
  }
  [StructLayout(LayoutKind.Sequential)]
  public struct NCB
  {
    public byte ncb_command;
    public byte ncb_retcode;
    public byte ncb_lsn;
    public byte ncb_num;
    public IntPtr ncb_buffer;
    public ushort ncb_length;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
    public byte[] ncb_callname;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NCBNAMSZ)]
    public byte[] ncb_name;
    public byte ncb_rto;
    public byte ncb_sto;
    public IntPtr ncb_post;
    public byte ncb_lana_num;
    public byte ncb_cmd_cplt;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=10)]
    public byte[] ncb_reserve;
    public IntPtr ncb_event;
  }
  [StructLayout(LayoutKind.Sequential)]
  public struct LANA_ENUM
  {
    public byte length;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.MAX_LANA)]
    public byte[] lana;
  }
  [StructLayout(LayoutKind.Auto)]
  public struct ASTAT
  {
    public ADAPTER_STATUS adapt;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=(int)NCBCONST.NUM_NAMEBUF)]
    public NAME_BUFFER[] NameBuff;
  }
  public class Win32API
  {
    [DllImport("NETAPI32.DLL")]
    public static extern char Netbios(ref NCB ncb);
  }
  //取网卡mac
  public string GetMacAddress()
  {
    string addr="";
    try
    {
      int cb;
      ASTAT adapter;
      NCB Ncb=new NCB();
      char uRetCode;
      LANA_ENUM lenum;
      Ncb.ncb_command = (byte)NCBCONST.NCBENUM;
      cb = Marshal.SizeOf(typeof(LANA_ENUM));
      Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
      Ncb.ncb_length = (ushort)cb;
      uRetCode = Win32API.Netbios(ref Ncb);
      lenum = (LANA_ENUM)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(LANA_ENUM));
      Marshal.FreeHGlobal(Ncb.ncb_buffer);
      if(uRetCode != (short)NCBCONST.NRC_GOODRET)
      return "";
      for(int i=0; i < lenum.length ;i++)
      {
        Ncb.ncb_command = (byte)NCBCONST.NCBRESET;
        Ncb.ncb_lana_num = lenum.lana[i];
        uRetCode = Win32API.Netbios(ref Ncb);
        if(uRetCode != (short)NCBCONST.NRC_GOODRET)
        return "";
        Ncb.ncb_command = (byte)NCBCONST.NCBASTAT;
        Ncb.ncb_lana_num = lenum.lana[i];
        Ncb.ncb_callname[0]=(byte)'*';
        cb = Marshal.SizeOf(typeof(ADAPTER_STATUS)) + Marshal.SizeOf(typeof(NAME_BUFFER))*(int)NCBCONST.NUM_NAMEBUF;
        Ncb.ncb_buffer = Marshal.AllocHGlobal(cb);
        Ncb.ncb_length = (ushort)cb;
        uRetCode = Win32API.Netbios(ref Ncb);
        adapter.adapt = (ADAPTER_STATUS)Marshal.PtrToStructure(Ncb.ncb_buffer, typeof(ADAPTER_STATUS));
        Marshal.FreeHGlobal(Ncb.ncb_buffer);
        if (uRetCode == (short)NCBCONST.NRC_GOODRET)
        {
          if(i>0)
          addr += ":";
          addr = string.Format("{0,2:X}{1,2:X}{2,2:X}{3,2:X}{4,2:X}{5,2:X}",
          adapter.adapt.adapter_address[0],
          adapter.adapt.adapter_address[1],
          adapter.adapt.adapter_address[2],
          adapter.adapt.adapter_address[3],
          adapter.adapt.adapter_address[4],
          adapter.adapt.adapter_address[5]);
        }
      }
    }
    catch
    {
    }
    return addr.Replace(' ', '0');
  }
}

更多关于C#相关内容感兴趣的读者可查看本站专题:《C#窗体操作技巧汇总》、《C#常见控件用法教程》、《WinForm控件用法总结》、《C#程序设计之线程使用技巧总结》、《C#操作Excel技巧总结》、《C#中XML文件操作技巧汇总》、《C#数据结构与算法教程》、《C#数组操作技巧总结》及《C#面向对象程序设计入门教程》

希望本文所述对大家C#程序设计有所帮助。

(0)

相关推荐

  • C#利用win32 Api 修改本地系统时间、获取硬盘序列号

    C#利用win32 Api 修改本地系统时间.获取硬盘序列号,可以用于软件注册机制的编写! 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace Fengyun {     public class Win32     {         #region 修改本地系统时间         [DllIm

  • C#获取CPU编号的方法

    本文实例讲述了C#获取CPU编号的方法.分享给大家供大家参考.具体如下: /// <summary> /// Gets the cpu 编号. ///需引用 using System.Management; /// </summary> /// <returns></returns> public string GetCpuId() { string cpuInfo = ""; ManagementClass cimobject = ne

  • C#如何取硬件标志

    using System; using System.Runtime.InteropServices; using  System.Management; namespace Hardware { /// <summary> /// Hardware_Mac 的摘要说明. /// </summary> public class HardwareInfo {   //取机器名    public string GetHostName()   {    return System.Ne

  • C#编程获取各种电脑硬件信息的方法示例

    本文实例讲述了C#编程获取各种电脑硬件信息的方法.分享给大家供大家参考,具体如下: 获取CPU编号: ManagementClass mc = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = mc.GetInstances(); string strID = null ; foreach( ManagementObject mo in moc ) { strID = mo.Properti

  • C#编程获取客户端计算机硬件及系统信息功能示例

    本文实例讲述了C#编程获取客户端计算机硬件及系统信息功能.分享给大家供大家参考,具体如下: 这里使用C#获取客户端计算机硬件及系统信息 ,包括CPU.硬盘.IP.MAC地址.操作系统等. 1.项目引用System.Management库. 2.创建HardwareHandler.cs类文件 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Manag

  • C#测量程序运行时间及cpu使用时间实例方法

    这里要指出的是, 运行一段程序,使用的cpu时间,跟实际运行的时间是不一样的.附例如下: 复制代码 代码如下: private void ShowRunTime()  {   TimeSpan ts1 = Process.GetCurrentProcess().TotalProcessorTime;   Stopwatch stw = new Stopwatch();  stw.Start();  int Circles = 1000;   for (int i = 0; i < Circles

  • 详解C#获取特定进程CPU和内存使用率

    首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程对象.当有了进程对象后,可以通过进程对象名称来创建PerformanceCounter类型对象,通过设定PerformanceCounter构造函数的参数实现获取特定进程的CPU和内存使用情况. 具体实例代码如下: 首先是获取本机中所有进程对象,分别输出某一时刻各个进程的内存使用情况: using

  • C#读取计算机CPU及HDD信息的方法

    本文实例讲述了C#读取计算机CPU及HDD信息的方法.分享给大家供大家参考.具体如下: 这里使用C#读取计算机CPU,HDD信息,适用于Windows public string getCpuInfo() //读取CPU信息 { ManagementClass mobj = new ManagementClass("Win32_Processor"); ManagementObjectCollection moc = mobj.GetInstances(); foreach (Mana

  • C#获取硬盘编号的方法

    本文实例讲述了C#获取硬盘编号的方法.分享给大家供大家参考.具体实现方法如下: ManagementClass mc = new ManagementClass("Win32_PhysicalMedia"); //Win32_DiskDrive不包含SerialNumber属性. ManagementObjectCollection moc = mc.GetInstances(); string strID = null ; foreach( ManagementObject mo i

  • C#获取计算机名,IP,MAC信息实现代码

    利用C#获取计算机名,IP,MAC信息,如下为源代码: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Management; namespace Wenanry.Net { /// <summary> /// 获取计算机系统信息 /// </summary> public class ManagementSyst

  • 用C#获取硬盘序列号,CPU序列号,网卡MAC地址的源码

    privatestring[]GetMoc() { string[]str=newstring[3]; ManagementClassmcCpu=newManagementClass("win32_Processor"); ManagementObjectCollectionmocCpu=mcCpu.GetInstances(); foreach(ManagementObjectminmocCpu) { str[0]=m["ProcessorId"].ToStrin

随机推荐