在這個程序當中,主要通過下面兩個類獲取用戶系統的信息:
System.Environment
System.Managememnt
應用程序包括三個tab菜單,分別是:
System
CPU
Local drives
在 System 菜單中,用 System.Environment 類來獲取系統信息 :
[csharp]
private string SystemInformation()
{
StringBuilder StringBuilder1 = new StringBuilder(string.Empty);
try
{
StringBuilder1.AppendFormat("Operation System: {0}\n", Environment.OSVersion);
if (Environment.Is64BitOperatingSystem)
StringBuilder1.AppendFormat("\t\t 64 Bit Operating System\n");
else
StringBuilder1.AppendFormat("\t\t 32 Bit Operating System\n");
StringBuilder1.AppendFormat("SystemDirectory: {0}\n", Environment.SystemDirectory);
StringBuilder1.AppendFormat("ProcessorCount: {0}\n", Environment.ProcessorCount);
StringBuilder1.AppendFormat("UserDomainName: {0}\n", Environment.UserDomainName);
StringBuilder1.AppendFormat("UserName: {0}\n", Environment.UserName);
//Drives
StringBuilder1.AppendFormat("LogicalDrives:\n");
foreach (System.IO.DriveInfo DriveInfo1 in System.IO.DriveInfo.GetDrives())
{
try
{
StringBuilder1.AppendFormat("\t Drive: {0}\n\t\t VolumeLabel: " +
"{1}\n\t\t DriveType: {2}\n\t\t DriveFormat: {3}\n\t\t " +
"TotalSize: {4}\n\t\t AvailableFreeSpace: {5}\n",
DriveInfo1.Name, DriveInfo1.VolumeLabel, DriveInfo1.DriveType,
DriveInfo1.DriveFormat, DriveInfo1.TotalSize, DriveInfo1.AvailableFreeSpace);
}
catch
{
}
}
StringBuilder1.AppendFormat("SystemPageSize: {0}\n", Environment.SystemPageSize);
StringBuilder1.AppendFormat("Version: {0}", Environment.Version);
}
catch
{
}
return StringBuilder1.ToString();
}
在 CPU 和 Local drive 選項卡, 類 System.Management 用來收集信息,但是在使用該類之前需要加入引用. 加入System.Management引用的步驟如下:
打開項目解決方案.
右鍵單擊引用,選擇添加引用.
單擊.NET 選項卡.
選擇System.Management.
單擊確定按鈕.
現在可以用該類寫下面的函數:
[csharp]
private string DeviceInformation(string stringIn)
{
StringBuilder StringBuilder1 = new StringBuilder(string.Empty);
ManagementClass ManagementClass1 = new ManagementClass(stringIn);
//Create a ManagementObjectCollection to loop through
ManagementObjectCollection ManagemenobjCol = ManagementClass1.GetInstances();
//Get the properties in the class
PropertyDataCollection properties = ManagementClass1.Properties;
foreach (ManagementObject obj in ManagemenobjCol)
{
foreach (PropertyData property in properties)
{
try
{
StringBuilder1.AppendLine(property.Name + ": " +
obj.Properties[property.Name].Value.ToString());
}
catch
{
//Add codes to manage more informations
}
}
StringBuilder1.AppendLine();
}
return StringBuilder1.ToString();
}
這個函數有一個參數,該參數的值可以是Win32_Processor 或Win32_LogicalDisk。用第一次參數來獲取CPU的信息,用第二參數來獲取硬盤驅動器的信息。最後再Window_Loaded函數中調用如下語句:
[csharp]
//System Information
textBox1.Text = SystemInformation();
//CPU Information
textBox2.Text = DeviceInformation("Win32_Processor");
//Local Drives Information
textBox3.Text = DeviceInformation("Win32_LogicalDisk");