using System;
using System.Management;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net.NetworkInformation;
using System.Text;
using TomTaw.Log;
namespace TomTaw.Common
{
/// <summary>
/// Computer Information
/// </summary>
public class ClientHardWare
{
private ManagementClass _mc;
private ManagementObjectCollection _moc;
#region 修改客户端时间
[DllImport("kernel32.dll")]
private static extern bool SetLocalTime(ref SYSTEMTIME time);
[StructLayout(LayoutKind.Sequential)]
private struct SYSTEMTIME
{
public short year;
public short month;
public short dayOfWeek;
public short day;
public short hour;
public short minute;
public short second;
public short milliseconds;
}
/// <summary>
/// 更新当前电脑系统时间
/// </summary>
/// <param name="dt"></param>
public static void SetDate(DateTime dt)
{
SYSTEMTIME st;
st.year = (short)dt.Year;
st.month = (short)dt.Month;
st.dayOfWeek = (short)dt.DayOfWeek;
st.day = (short)dt.Day;
st.hour = (short)dt.Hour;
st.minute = (short)dt.Minute;
st.second = (short)dt.Second;
st.milliseconds = (short)dt.Millisecond;
SetLocalTime(ref st);
}
#endregion
/// <summary>
/// 获取CPU序列号代码
/// </summary>
/// <returns></returns>
public string GetCpuID()
{
try
{
string sCpuInfo = string.Empty;//cpu序列号
_mc = new ManagementClass("Win32_Processor");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc) //获取CPU序列号代码
{
sCpuInfo = mo.Properties["ProcessorId"].Value.ToString();
}
_moc = null;
_mc = null;
return sCpuInfo;
}
catch { return string.Empty; }
}
[DllImport("iphlpapi.dll")]
private static extern int GetAdaptersInfo(IntPtr pAdapterInfo, ref Int64 pBufOutLen);
private const int MAX_ADAPTER_DESCRIPTION_LENGTH = 128;
private const int ERROR_BUFFER_OVERFLOW = 111;
private const int MAX_ADAPTER_NAME_LENGTH = 256;
private const int MAX_ADAPTER_ADDRESS_LENGTH = 8;
private const int MIB_IF_TYPE_OTHER = 1;
private const int MIB_IF_TYPE_ETHERNET = 6;
private const int MIB_IF_TYPE_TOKENRING = 9;
private const int MIB_IF_TYPE_FDDI = 15;
private const int MIB_IF_TYPE_PPP = 23;
private const int MIB_IF_TYPE_LOOPBACK = 24;
private const int MIB_IF_TYPE_SLIP = 28;
[StructLayout(LayoutKind.Sequential)]
private struct IP_ADDRESS_STRING
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
public string Address;
}
[StructLayout(LayoutKind.Sequential)]
private struct IP_ADDR_STRING
{
public IntPtr Next;
public IP_ADDRESS_STRING IpAddress;
public IP_ADDRESS_STRING IpMask;
public Int32 Context;
}
[StructLayout(LayoutKind.Sequential)]
private struct IP_ADAPTER_INFO
{
public IntPtr Next;
public Int32 ComboIndex;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ADAPTER_NAME_LENGTH + 4)]
public string AdapterName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = MAX_ADAPTER_DESCRIPTION_LENGTH + 4)]
public string AdapterDescription;
public UInt32 AddressLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)]
public byte[] Address;
public Int32 Index;
public UInt32 Type;
public UInt32 DhcpEnabled;
public IntPtr CurrentIpAddress;
public IP_ADDR_STRING IpAddressList;
public IP_ADDR_STRING GatewayList;
public IP_ADDR_STRING DhcpServer;
public bool HaveWins;
public IP_ADDR_STRING PrimaryWinsServer;
public IP_ADDR_STRING SecondaryWinsServer;
public Int32 LeaseObtained;
public Int32 LeaseExpires;
}
///// <summary>
///// 获取本地物理网卡MAC地址,物理网卡不启动失效
///// </summary>
///// <returns>物理网卡MAC</returns>
//public string GetMacAddress()
//{
// string sMac = string.Empty;
// long structSize = Marshal.SizeOf(typeof(IP_ADAPTER_INFO));
// IntPtr pArray = Marshal.AllocHGlobal((int)new IntPtr(structSize));
// int ret = GetAdaptersInfo(pArray, ref structSize);
// if (ret == ERROR_BUFFER_OVERFLOW) // ERROR_BUFFER_OVERFLOW == 111
// {
// // Buffer was too small, reallocate the correct size for the buffer.
// pArray = Marshal.ReAllocHGlobal(pArray, new IntPtr(structSize));
// ret = GetAdaptersInfo(pArray, ref structSize);
// } // if
// if (ret == 0)
// {
// // Call Succeeded
// IntPtr pEntry = pArray;
// // Retrieve the adapter info from the memory address
// IP_ADAPTER_INFO entry = (IP_ADAPTER_INFO)Marshal.PtrToStructure(pEntry, typeof(IP_ADAPTER_INFO));
// // MAC Address (data is in a byte[])
// string tmpString = string.Empty;
// for (int i = 0; i < entry.AddressLength - 1; i++)
// {
// tmpString += string.Format("{0:X2}:", entry.Address[i]);
// }
// sMac = string.Format("{0}{1:X2}", tmpString, entry.Address[entry.AddressLength - 1]);
// }
// else
// {
// Marshal.FreeHGlobal(pArray);
// throw new InvalidOperationException("GetAdaptersInfo failed: " + ret);
// }
// return sMac;
//}
/// <summary>
/// 获取网卡硬件地址(Mac)
/// </summary>
/// <returns></returns>
public string GetMacAddress()
{
string sMac = string.Empty;
try
{
_mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc) //获取网卡硬件地址
{
if ((bool)mo["IPEnabled"] == true)
{
sMac = mo["MacAddress"].ToString();
if (string.IsNullOrEmpty(sMac)) continue;
break;
}
}
_moc = null;
_mc = null;
}
catch (Exception ex)
{
LogManager.Log("ClientHardWare", "GetMacAddress", LogLevel.Debug, "GetInstances获取网卡地址失败", ex.ToString());
}
if (sMac.IsNullOrEmptyTrim()) //如果是WIN7单机版则使用DOS命令取网卡地址
{
try
{
sMac = GetMacByIPConfig(); //获取Mac地址,IP,状态
}
catch { return string.Empty; }
}
return sMac;
}
/// <summary>
/// 根据截取ipconfig /all命令的输出流获取网卡Mac
/// </summary>
/// <returns></returns>
public string GetMacByIPConfig()
{
string sMac = string.Empty;
ProcessStartInfo startInfo = new ProcessStartInfo("ipconfig", "/all");
startInfo.UseShellExecute = false;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
Process p = Process.Start(startInfo);
//截取输出流
StreamReader reader = p.StandardOutput;
string line = reader.ReadLine();
while (!reader.EndOfStream)
{
if (!string.IsNullOrEmpty(line))
{
line = line.Trim();
if (line.StartsWith("Physical Address") || line.StartsWith("物理地址"))
{
sMac = line.Substring(line.IndexOf(":") + 1, line.Length - line.IndexOf(":") - 1).Replace("-", ":");
break;
}
}
line = reader.ReadLine();
}
//等待程序执行完退出进程
p.WaitForExit();
p.Close();
reader.Close();
return sMac.Trim();
}
/// <summary>
/// 获取IP地址
/// </summary>
/// <returns></returns>
public string GetIPAddress()
{
try
{
string sIP = string.Empty; //获取IP地址
_mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc)
{
if ((bool)mo["IPEnabled"] == true)
{
Array ar;
ar = (System.Array)(mo.Properties["IpAddress"].Value);
sIP = ar.GetValue(0).ToString();
if (sIP == "0.0.0.0") continue;
break;
}
}
_moc = null;
_mc = null;
return sIP;
}
catch { return string.Empty; }
}
/// <summary>
/// 获取硬盘ID
/// </summary>
/// <returns></returns>
public string GetDiskID()
{
try
{
String sHDid = string.Empty; //获取硬盘ID
_mc = new ManagementClass("Win32_DiskDrive");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc)
{
sHDid = (string)mo.Properties["Model"].Value;
}
_moc = null;
_mc = null;
return sHDid;
}
catch { return string.Empty; }
}
/// <summary>
/// 操作系统的登录用户名
/// </summary>
/// <returns></returns>
public string GetUserName()
{
try
{
string sUser = string.Empty;
_mc = new ManagementClass("Win32_ComputerSystem");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc)
{
sUser = mo["UserName"].ToString();
}
_moc = null;
_mc = null;
return sUser;
}
catch { return string.Empty; }
}
/// <summary>
/// PC类型
/// </summary>
/// <returns></returns>
public string GetSystemType()
{
try
{
string sSysType = string.Empty;
_mc = new ManagementClass("Win32_ComputerSystem");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc)
{
sSysType = mo["SystemType"].ToString();
}
_moc = null;
_mc = null;
return sSysType;
}
catch { return string.Empty; }
}
/// <summary>
/// 物理内存
/// </summary>
/// <returns></returns>
public string GetTotalPhysicalMemory()
{
try
{
string sPhyMemo = string.Empty;
_mc = new ManagementClass("Win32_ComputerSystem");
_moc = _mc.GetInstances();
foreach (ManagementObject mo in _moc)
{
sPhyMemo = mo["TotalPhysicalMemory"].ToString();
}
_moc = null;
_mc = null;
return sPhyMemo;
}
catch { return string.Empty; }
}
/// <summary>
/// 获取主机名
/// </summary>
/// <returns></returns>
public string GetComputerName()
{
try
{
return System.Environment.GetEnvironmentVariable("ComputerName");
}
catch { return string.Empty; }
}
}
}