天天看点

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

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

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(“\tprimary {0}”, screen.primary); 

     console.writeline(“\tbounds: {0}”, screen.bounds); 

     console.writeline(“\tworking area: {0}”,screen.workingarea); 

     console.writeline(“\tbitsperpixel: {0}”,screen.bitsperpixel); 

3 读取注册表键值对

using (registrykey keyrun = registry.localmachine.opensubkey(@”software\microsoft\windows\currentversion\run”)) 

    foreach (string valuename in keyrun.getvaluenames()) 

     console.writeline(“name: {0}\tvalue: {1}”, valuename, keyrun.getvalue(valuename)); 

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

4 启动,停止windows服务

这项api提供的实用功能常常用来管理应用程序中的服务,而不必到控制面板的管理服务中进行操作。

servicecontroller controller = new servicecontroller(“e-m-power”);      

controller.start();      

if (controller.canpauseandcontinue)      

{      

    controller.pause();      

    controller.continue();      

}      

controller.stop();       

.net提供的api中,可以实现一句话安装与卸载服务

if (args[0] == "/i") 

       managedinstallerclass.installhelper(new string[] { assembly.getexecutingassembly().location }); 

else if (args[0] == "/u") 

   managedinstallerclass.installhelper(new string[] { "/u", assembly.getexecutingassembly().location }); 

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

5 验证程序是否有strong name (p/invoke)

比如在程序中,为了验证程序集是否有签名,可调用如下方法

[dllimport("mscoree.dll", charset=charset.unicode)] 

static extern bool strongnamesignatureverificationex(string wszfilepath, bool fforceverification, ref bool  pfwasverified); 

bool notforced = false; 

bool verified = strongnamesignatureverificationex(assembly, false, ref notforced); 

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系统引入一些新特性,比如打开文件对话框,状态栏可显示当前任务的进度。

microsoft.windowsapicodepack.dialogs.commonopenfiledialog ofd = new  microsoft.windowsapicodepack.dialogs.commonopenfiledialog(); 

ofd.addtomostrecentlyusedlist = true; 

ofd.isfolderpicker = true; 

ofd.allownonfilesystemitems = true; 

ofd.showdialog(); 

用这样的方法打开对话框,与bcl自带类库中的openfiledialog功能更多一些。不过只限于windows

7系统中,所以要调用这段代码,还要检查操作系统的版本要大于6,并且添加对程序集windows api code pack for

8 检查程序对内存的消耗

用下面的方法,可以检查.net给程序分配的内存数量

long available = gc.gettotalmemory(false); 

console.writeline(“before allocations: {0:n0}”, available); 

int allocsize = 40000000; 

byte[] bigarray = new byte[allocsize]; 

available = gc.gettotalmemory(false); 

console.writeline(“after allocations: {0:n0}”, available); 

在我的系统中,它运行的结果如下所示

before allocations: 651,064 

after allocations: 40,690,080 

使用下面的方法,可以检查当前应用程序占用的内存

process proc = process.getcurrentprocess(); 

console.writeline(“process info: “+environment.newline+  

 “private memory size: {0:n0}”+environment.newline + 

“virtual memory size: {1:n0}” + environment.newline + 

“working set size: {2:n0}” + environment.newline + 

“paged memory size: {3:n0}” + environment.newline + 

“paged system memory size: {4:n0}” + environment.newline + 

  “non-paged system memory size: {5:n0}” + environment.newline, 

proc.privatememorysize64,   proc.virtualmemorysize64,  proc.workingset64,  proc.pagedmemorysize64, proc.pagedsystemmemorysize64,  proc.nonpagedsystemmemorysize64 ); 

9 使用记秒表检查程序运行时间

如果你担忧某些代码非常耗费时间,可以用stopwatch来检查这段代码消耗的时间,如下面的代码所示

system.diagnostics.stopwatch timer = new system.diagnostics.stopwatch(); 

timer.start(); 

decimal total = 0; 

int limit = 1000000; 

for (int i = 0; i < limit; ++i) 

      total = total + (decimal)math.sqrt(i); 

timer.stop(); 

console.writeline(“sum of sqrts: {0}”,total); 

console.writeline(“elapsed milliseconds: {0}”, 

timer.elapsedmilliseconds); 

console.writeline(“elapsed time: {0}”, timer.elapsed); 

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

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

class autostopwatch : system.diagnostics.stopwatch, idisposable 

   public autostopwatch() 

       start(); 

   } 

   public void dispose() 

       stop(); 

       console.writeline(“elapsed: {0}”, this.elapsed); 

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

using (new autostopwatch()) 

    decimal total2 = 0; 

    int limit2 = 1000000; 

    for (int i = 0; i < limit2; ++i) 

       total2 = total2 + (decimal)math.sqrt(i); 

10 使用光标

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

class autowaitcursor : idisposable 

private control _target; 

private cursor _prevcursor = cursors.default; 

public autowaitcursor(control control) 

   if (control == null) 

     throw new argumentnullexception(“control”); 

   _target = control; 

   _prevcursor = _target.cursor; 

   _target.cursor = cursors.waitcursor; 

public void dispose() 

   _target.cursor = _prevcursor; 

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

using (new autowaitcursor(this)) 

... 

throw new exception(); 

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

来源:51cto

继续阅读