C#程序员经常用到的10个实用代码片段

开发 后端
如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间。以下是原文:

如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间。以下是原文:

[[145804]]

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系统中,输出以下信息

  1. Platform: Win32NT 
  2. Service Pack: 
  3. Version: 6.1.7600.0 
  4. VersionString: Microsoft Windows NT 6.1.7600.0 
  5. CLR Version: 4.0.21006.1 

2 读取CPU数量,内存容量

可以通过Windows Management Instrumentation (WMI)提供的接口读取所需要的信息。

  1. private static UInt32 CountPhysicalProcessors() 
  2.      ManagementObjectSearcher objects = new ManagementObjectSearcher( 
  3.         “SELECT * FROM Win32_ComputerSystem”); 
  4.      ManagementObjectCollection coll = objects.Get(); 
  5.      foreach(ManagementObject obj in coll) 
  6.     { 
  7.         return (UInt32)obj[“NumberOfProcessors”]; 
  8.     } 
  9.     return 0
  10. private static UInt64 CountPhysicalMemory() 
  11.    ManagementObjectSearcher objects =new ManagementObjectSearcher( 
  12.       “SELECT * FROM Win32_PhysicalMemory”); 
  13.    ManagementObjectCollection coll = objects.Get(); 
  14.    UInt64 total = 0
  15.    foreach (ManagementObject obj in coll) 
  16.    { 
  17.        total += (UInt64)obj[“Capacity”]; 
  18.     } 
  19.     return total; 

请添加对程序集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.      Console.WriteLine(“Screen {0}”, screen.DeviceName); 
  10.      Console.WriteLine(“\tPrimary {0}”, screen.Primary); 
  11.      Console.WriteLine(“\tBounds: {0}”, screen.Bounds); 
  12.      Console.WriteLine(“\tWorking Area: {0}”,screen.WorkingArea); 
  13.      Console.WriteLine(“\tBitsPerPixel: {0}”,screen.BitsPerPixel); 

3 读取注册表键值对

  1. using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”)) 
  2.     foreach (string valueName in keyRun.GetValueNames()) 
  3.     { 
  4.      Console.WriteLine(“Name: {0}\tValue: {1}”, valueName, keyRun.GetValue(valueName)); 
  5.     } 

请添加命名空间Microsoft.Win32,以确保上面的代码可以编译。

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中,可以实现一句话安装与卸载服务

  1. if (args[0] == "/i"
  2.        ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); 
  3. else if (args[0] == "/u"
  4.    ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); 

如代码所示,给应用程序传入i或u参数,以表示是卸载或是安装程序。

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.       total = total + (Decimal)Math.Sqrt(i); 
  7. timer.Stop(); 
  8. Console.WriteLine(“Sum of sqrts: {0}”,total); 
  9. Console.WriteLine(“Elapsed milliseconds: {0}”, 
  10. timer.ElapsedMilliseconds); 
  11. Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed); 

现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。

以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。

  1. class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable 
  2.    public AutoStopwatch() 
  3.    { 
  4.        Start(); 
  5.    } 
  6.    public void Dispose() 
  7.    { 
  8.        Stop(); 
  9.        Console.WriteLine(“Elapsed: {0}”, this.Elapsed); 
  10.    } 

借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。

  1. using (new AutoStopwatch()) 
  2.     Decimal total2 = 0
  3.     int limit2 = 1000000
  4.     for (int i = 0; i < limit2; ++i) 
  5.     { 
  6.        total2 = total2 + (Decimal)Math.Sqrt(i); 
  7.     } 

10 使用光标

当程序正在后台运行保存或是册除操作时,应当将光标状态修改为忙碌。可使用下面的技巧。

  1. class AutoWaitCursor : IDisposable 
  2. private Control _target; 
  3. private Cursor _prevCursor = Cursors.Default; 
  4. public AutoWaitCursor(Control control) 
  5.    if (control == null
  6.    { 
  7.      throw new ArgumentNullException(“control”); 
  8.    } 
  9.    _target = control; 
  10.    _prevCursor = _target.Cursor; 
  11.    _target.Cursor = Cursors.WaitCursor; 
  12. public void Dispose() 
  13.    _target.Cursor = _prevCursor; 

用法如下所示,这个写法,是为了预料到程序可能会抛出异常

  1. using (new AutoWaitCursor(this)) 
  2. ... 
  3. throw new Exception(); 

如代码所示,即使抛出异常,光标也可以恢复到之间的状态。

责任编辑:王雪燕 来源: James Li
相关推荐

2015-10-29 10:30:41

C#程序员实用代码

2015-10-08 08:53:46

PHP代码片段

2011-07-07 10:35:53

htaccess

2014-05-13 13:09:23

Python程序员

2020-11-16 16:04:42

CSS设计代码

2021-09-17 15:31:47

代码JavaScript数组

2020-11-11 08:38:45

作图软件

2011-07-07 17:24:28

PHP

2011-07-07 17:27:54

PHP

2021-09-02 08:40:10

程序员错误

2015-11-02 09:25:07

jQuery代码片段

2010-08-10 09:51:19

C#代码

2010-08-11 09:51:28

Flex代码

2015-06-12 11:22:52

程序员程序员跳槽

2011-11-23 09:21:43

jQuery

2020-10-05 21:13:37

程序员技能开发者

2011-07-14 10:07:19

PHP

2023-06-16 16:34:25

JavaScripWeb 开发

2024-01-04 16:46:58

JavaScript开发

2023-11-03 16:02:00

JavaScript开发
点赞
收藏

51CTO技术栈公众号