C#程序员经常用到的程序员经常用到的10个实用代码片段个实用代码片段
如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应
用,这些代码也许能给你的开发节省不少时间。以下是原文:
1 读取操作系统和CLR的版本
OperatingSystem os = System.Environment.OSVersion;
Console.WriteLine(“Platform: {0}”, os.Platform);
Console.WriteLine(“Service Pack: {0}”, os.ServicePack);
Console.WriteLine(“Version: {0}”, os.Version);
Console.WriteLine(“VersionString: {0}”, os.VersionString);
Console.WriteLine(“CLR Version: {0}”, System.Environment.Version);
在我的Windows 7系统中,输出以下信息
Platform: Win32NT
Service Pack:
Version: 6.1.7600.0
VersionString: Microsoft Windows NT 6.1.7600.0
CLR Version: 4.0.21006.1
2 读取CPU数量,内存容量
可以通过Windows Management Instrumentation (WMI)提供的接口读取所需要的信息。
private static UInt32 CountPhysicalProcessors()
{
ManagementObjectSearcher objects = new ManagementObjectSearcher(
“SELECT * FROM Win32_ComputerSystem”);
ManagementObjectCollection coll = objects.Get();
foreach(ManagementObject obj in coll)
{
return (UInt32)obj[“NumberOfProcessors”];
}
return 0;
}
private static UInt64 CountPhysicalMemory()
{
ManagementObjectSearcher objects =new ManagementObjectSearcher(
“SELECT * FROM Win32_PhysicalMemory”);
ManagementObjectCollection coll = objects.Get();
UInt64 total = 0;
foreach (ManagementObject obj in coll)
{
total += (UInt64)obj[“Capacity”];
}
return total;
}
请添加对程序集System.Management的引用,确保代码可以正确编译。
Console.WriteLine(“Machine: {0}”, Environment.MachineName);
Console.WriteLine(“# of processors (logical): {0}”, Environment.ProcessorCount);
Console.WriteLine(“# of processors (physical): {0}” CountPhysicalProcessors());
Console.WriteLine(“RAM installed: {0:N0} bytes”, CountPhysicalMemory());
Console.WriteLine(“Is OS 64-bit? {0}”, Environment.Is64BitOperatingSystem);
Console.WriteLine(“Is process 64-bit? {0}”, Environment.Is64BitProcess);
Console.WriteLine(“Little-endian: {0}”, BitConverter.IsLittleEndian);
foreach (Screen screen in System.Windows.Forms.Screen.AllScreens)
{
Console.WriteLine(“Screen {0}”, screen.DeviceName);
Console.WriteLine(“ Primary {0}”, screen.Primary);
Console.WriteLine(“ Bounds: {0}”, screen.Bounds);
Console.WriteLine(“ Working Area: {0}”,screen.WorkingArea);
Console.WriteLine(“ BitsPerPixel: {0}”,screen.BitsPerPixel);
}
3 读取注册表键值对
using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”SoftwareMicrosoftWindowsCurrentVersionRun”))
{
foreach (string valueName in keyRun.GetValueNames())
{
Console.WriteLine(“Name: {0} Value: {1}”, valueName, keyRun.GetValue(valueName));
}
}
请添加命名空间Microsoft.Win32,以确保上面的代码可以编译。