原文地址
如果你是一個C#程序員,那么本文介紹的10個C#常用代碼片段一定會給你帶來幫助,從底層的資源操作,到上層的UI應用,這些代碼也許能給你的開發節省不少時間。以下是原文:
1 讀取操作系統和CLR的版本
1 OperatingSystem os = System.Environment.OSVersion; 2 Console.WriteLine(“Platform: {0}”, os.Platform); 3 Console.WriteLine(“Service Pack: {0}”, os.ServicePack); 4 Console.WriteLine(“Version: {0}”, os.Version); 5 Console.WriteLine(“VersionString: {0}”, os.VersionString); 6 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
讀取CPU數量,內存容量
可以通過Windows Management Instrumentation (WMI)提供的接口讀取所需要的信息。
1 private static UInt32 CountPhysicalProcessors() 2 { 3 ManagementObjectSearcher objects = new ManagementObjectSearcher( 4 “SELECT * FROM Win32_ComputerSystem”); 5 ManagementObjectCollection coll = objects.Get(); 6 foreach(ManagementObject obj in coll) 7 { 8 return (UInt32)obj[“NumberOfProcessors”]; 9 } 10 return 0; 11 } 12 private static UInt64 CountPhysicalMemory() 13 { 14 ManagementObjectSearcher objects =new ManagementObjectSearcher( 15 “SELECT * FROM Win32_PhysicalMemory”); 16 ManagementObjectCollection coll = objects.Get(); 17 UInt64 total = 0; 18 foreach (ManagementObject obj in coll) 19 { 20 total += (UInt64)obj[“Capacity”]; 21 } 22 return total; 23 }
請添加對程序集System.Management的引用,確保代碼可以正確編譯。
1 Console.WriteLine(“Machine: {0}”, Environment.MachineName); 2 Console.WriteLine(“# of processors (logical): {0}”, Environment.ProcessorCount); 3 Console.WriteLine(“# of processors (physical): {0}” CountPhysicalProcessors()); 4 Console.WriteLine(“RAM installed: {0:N0} bytes”, CountPhysicalMemory()); 5 Console.WriteLine(“Is OS 64-bit? {0}”, Environment.Is64BitOperatingSystem); 6 Console.WriteLine(“Is process 64-bit? {0}”, Environment.Is64BitProcess); 7 Console.WriteLine(“Little-endian: {0}”, BitConverter.IsLittleEndian); 8 foreach (Screen screen in System.Windows.Forms.Screen.AllScreens) 9 { 10 Console.WriteLine(“Screen {0}”, screen.DeviceName); 11 Console.WriteLine(“\tPrimary {0}”, screen.Primary); 12 Console.WriteLine(“\tBounds: {0}”, screen.Bounds); 13 Console.WriteLine(“\tWorking Area: {0}”,screen.WorkingArea); 14 Console.WriteLine(“\tBitsPerPixel: {0}”,screen.BitsPerPixel); 15 }
3 讀取注冊表鍵值對
// 請添加命名空間Microsoft.Win32,以確保上面的代碼可以編譯。
1 using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”)) 2 { 3 foreach (string valueName in keyRun.GetValueNames()) 4 { 5 Console.WriteLine(“Name: {0}\tValue: {1}”, valueName, keyRun.GetValue(valueName)); 6 } 7 }
4 啟動,停止Windows服務
這項API提供的實用功能常常用來管理應用程序中的服務,而不必到控制面板的管理服務中進行操作。
1 ServiceController controller = new ServiceController(“e-M-POWER”); 2 controller.Start(); 3 if (controller.CanPauseAndContinue) 4 { 5 controller.Pause(); 6 controller.Continue(); 7 } 8 controller.Stop();
.net提供的API中,可以實現一句話安裝與卸載服務
// 如代碼所示,給應用程序傳入i或u參數,以表示是卸載或是安裝程序。
1 if (args[0] == "/i") 2 { 3 ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); 4 } 5 else if (args[0] == "/u") 6 { 7 ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); 8
5 驗證程序是否有strong name (P/Invoke)
比如在程序中,為了驗證程序集是否有簽名,可調用如下方法:
1 [DllImport("mscoree.dll", CharSet=CharSet.Unicode)] 2 static extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool pfWasVerified); 3 4 bool notForced = false; 5 bool verified = StrongNameSignatureVerificationEx(assembly, false, ref notForced); 6 Console.WriteLine("Verified: {0}\nForced: {1}", verified, !notForced);
這個功能常用在軟件保護方法,可用來驗證簽名的組件。即使你的簽名被人去掉,或是所有程序集的簽名都被去除,只要程序中有這一項調用代碼,則可以停止程序運行。
6 響應系統配置項的變更
比如我們鎖定系統后,如果QQ沒有退出,則它會顯示了忙碌狀態。
請添加命名空間Microsoft.Win32,然后對注冊下面的事件。
. DisplaySettingsChanged (包含Changing) 顯示設置
. InstalledFontsChanged 字體變化
. PaletteChanged
. PowerModeChanged 電源狀態
. SessionEnded (用戶正在登出或是會話結束)
. SessionSwitch (變更當前用戶)
. TimeChanged 時間改變
. UserPreferenceChanged (用戶偏號 包含Changing)
我們的ERP系統,會監測系統時間是否改變,如果將時間調整后ERP許可文件之外的范圍,會導致ERP軟件不可用。
7 運用Windows7的新特性
Windows7系統引入一些新特性,比如打開文件對話框,狀態欄可顯示當前任務的進度。
1 Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd =new Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog(); 2 ofd.AddToMostRecentlyUsedList = true; 3 ofd.IsFolderPicker = true; 4 ofd.AllowNonFileSystemItems = true; 5 ofd.ShowDialog();
用這樣的方法打開對話框,與BCL自帶類庫中的OpenFileDialog功能更多一些。不過只限於Windows 7系統中,所以要調用這段代碼,還要檢查操作系統的版本要大於6,並且添加對程序集Windows API Code Pack for Microsoft®.NET Framework的引用,請到這個地址下載 http://code.msdn.microsoft.com/WindowsAPICodePack
8 檢查程序對內存的消耗
用下面的方法,可以檢查.NET給程序分配的內存數量:
1 long available = GC.GetTotalMemory(false); 2 Console.WriteLine(“Before allocations: {0:N0}”, available); 3 int allocSize = 40000000; 4 byte[] bigArray = new byte[allocSize]; 5 available = GC.GetTotalMemory(false); 6 Console.WriteLine(“After allocations: {0:N0}”, available);
在我的系統中,它運行的結果如下所示:
Before allocations: 651,064 After allocations: 40,690,080
使用下面的方法,可以檢查當前應用程序占用的內存:
1 Process proc = Process.GetCurrentProcess(); 2 Console.WriteLine(“Process Info: “+Environment.NewLine+ 3 “Private Memory Size: {0:N0}”+Environment.NewLine + 4 “Virtual Memory Size: {1:N0}” + Environment.NewLine + 5 “Working Set Size: {2:N0}” + Environment.NewLine + 6 “Paged Memory Size: {3:N0}” + Environment.NewLine + 7 “Paged System Memory Size: {4:N0}” + Environment.NewLine + 8 “Non-paged System Memory Size: {5:N0}” + Environment.NewLine, 9 proc.PrivateMemorySize64, proc.VirtualMemorySize64, proc.WorkingSet64, proc.PagedMemorySize64, proc.PagedSystemMemorySize64, proc.NonpagedSystemMemorySize64 );
9 使用記秒表檢查程序運行時間
如果你擔憂某些代碼非常耗費時間,可以用StopWatch來檢查這段代碼消耗的時間,如下面的代碼所示:
1 System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); 2 timer.Start(); 3 Decimal total = 0; 4 int limit = 1000000; 5 for (int i = 0; i < limit; ++i) 6 { 7 total = total + (Decimal)Math.Sqrt(i); 8 } 9 timer.Stop(); 10 Console.WriteLine(“Sum of sqrts: {0}”,total); 11 Console.WriteLine(“Elapsed milliseconds: {0}”, 12 timer.ElapsedMilliseconds); 13 Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed);
現在已經有專門的工具來檢測程序的運行時間,可以細化到每個方法,比如dotNetPerformance軟件。
以上面的代碼為例子,您需要直接修改源代碼,如果是用來測試程序,則有些不方便。請參考下面的例子。
1 class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable 2 { 3 public AutoStopwatch() 4 { 5 Start(); 6 } 7 public void Dispose() 8 { 9 Stop(); 10 Console.WriteLine(“Elapsed: {0}”, this.Elapsed); 11 } 12 }
借助於using語法,像下面的代碼所示,可以檢查一段代碼的運行時間,並打印在控制台上。
1 using (new AutoStopwatch()) 2 { 3 Decimal total2 = 0; 4 int limit2 = 1000000; 5 for (int i = 0; i < limit2; ++i) 6 { 7 total2 = total2 + (Decimal)Math.Sqrt(i); 8 } 9 }
10 使用光標
當程序正在后台運行保存或是冊除操作時,應當將光標狀態修改為忙碌。可使用下面的技巧。
1 class AutoWaitCursor : IDisposable 2 { 3 private Control _target; 4 private Cursor _prevCursor = Cursors.Default; 5 public AutoWaitCursor(Control control) 6 { 7 if (control == null) 8 { 9 throw new ArgumentNullException(“control”); 10 } 11 _target = control; 12 _prevCursor = _target.Cursor; 13 _target.Cursor = Cursors.WaitCursor; 14 } 15 public void Dispose() 16 { 17 _target.Cursor = _prevCursor; 18 } 19 }
用法如下所示,這個寫法,是為了預料到程序可能會拋出異常:
1 using (new AutoWaitCursor(this)) 2 { 3 ... 4 throw new Exception(); 5 }
如代碼所示,即使拋出異常,光標也可以恢復到之間的狀態。
轉載來源
http://blog.csdn.net/honantic/article/details/49337857