C#程序开发中常常遇到的10条实用的代码
1读取操作系统和CLR的版本OperatingSystemos=Version;iteLine(“Platform:{0}”,atform);iteLine(“ServicePack:{0}”,rvicePack);iteLine(“Version:{0}”,rsion);iteLine(“VersionString:{0}”,rsionString);iteLine(“CLRVersion:{0}”,rsion);在我的Windows7系统中,输出以下信息
Platform:Win32NTServicePack:Version:6.1..0VersionString:MicrosoftWindowsNT6.1..0CLRVersion:4.0..1
2读取CPU数量,内存容量可以通过WindowsManagementInstrumentation(WMI)提供的接口读取所需要的信息。
privatestaticUInt32CountPhysicalProcessors(){ManagementObjectSearcherobjects=newManagementObjectSearcher(“SELECT*FROMWin32_ComputerSystem”);ManagementObjectCollectioncoll=t();foreach(ManagementObjectobjincoll){return(UInt32)obj[“NumberOfProcessors”];}return0;}privatestaticUInt64CountPhysicalMemory(){ManagementObjectSearcherobjects=newManagementObjectSearcher(“SELECT*FROMWin32_PhysicalMemory”);ManagementObjectCollectioncoll=t();UInt64total=0;foreach(ManagementObjectobjincoll){total+=(UInt64)obj[“Capacity”];}returntotal;}请添加对程序集nagement的援用,确保代码可以正确编译。
iteLine(“Machine:{0}”,chineName);iteLine(“#ofprocessors(logical):{0}”,ocessorCount);iteLine(“#ofprocessors(physical):{0}”CountPhysicalProcessors());iteLine(“RAMinstalled:{0:N0}bytes”,CountPhysicalMemory());iteLine(“IsOS64-bit?{0}”,64BitOperatingSystem);iteLine(“Isprocess64-bit?{0}”,64BitProcess);iteLine(“Little-endian:{0}”,LittleEndian);foreach(lScreens){iteLine(“Screen{0}”,viceName);iteLine(“\tPrimary{0}”,imary);iteLine(“\tBounds:{0}”,unds);iteLine(“\tWorkingArea:{0}”,rkingArea);iteLine(“\tBitsPerPixel:{0}”,tsPerPixel);}3读取注册表键值对using(RegistryKeykeyRun=enSubKey(
”Software\Microsoft\Windows\CurrentVersion\Run”)){foreach(tValueNames()){iteLine(“Name:{0}\tValue:{1}”,valueName,tValue(valueName));}}请添加命名空间n32,以确保上面的代码可以编译。
4启动,停止Windows服务这项API提供的实用功能常常用来管理应用程序中的服务,而没必要到控制面板的管理服务中进行操作。
ServiceControllercontroller=newServiceController(“e-M-POWER”);art();if(nPauseAndContinue){use();ntinue();}op();.提供的API中,可以实现一句话安装与卸载服务
if(args[0]==/i){stallHelper(newstring[]{tExecutingAssembly().Location});}elseif(args[0]==/u){stallHelper(newstring[]{/u,tExecutingAssembly().Location});}如代码所示,给应用程序传入i或u参数,以表示是卸载或是安装程序。
5验证程序是不是有strongname(P/Invoke)比如在程序中,为了验证程序集是不是有签名,可调用以下方法
[DllImport(l,CharSet=icode)]staticexternboolStrongNameSignatureVerificationEx(stringwszFilePath,boolfForceVerification,refboolpfWasVerified);boolnotForced=false;boolverified=StrongNameSignatureVerificationEx(assembly,false,refnotForced);iteLine(Verified:{0}\nForced:{1},verified,!notForced);这个功能经常使用在软件保护方法,可用来验证签名的组件。即便你的签名被人去掉,或是所有程序集的签名都被去除,只要程序中有这一项调用代码,则可以停止程序运行。
6响应系统配置项的变更比如我们锁定系统后,如果没有退出,则它会显示了劳碌状态。
请添加命名空间n32,然后对注册下面的事件。
.DisplaySettingsChanged(包括Changing)显示设置.InstalledFontsChanged字体变化.werModeChanged电源状态.SessionEnded(用户正在登出或是会话结束).SessionSwitch(变更当前用户).TimeChanged时间改变.UserPreferenceChanged(用户偏号包括Changing)
我们的ERP系统,会监测系统时间是不是改变,如果将时间调剂后ERP许可文件以外的范围,会致使ERP软件不可用。
7应用Windows7的新特性Windows7系统引入一些新特性,比如打开文件对话框,状态栏可显示当前任务的进度。
monOpenFileDialogofd=monOpenFileDialog();dToMostRecentlyUsedList=true;FolderPicker=true;lowNonFileSystemItems=true;owDialog();用这样的方法打开对话框,与BCL自带类库中的OpenFileDialog功能更多一些。不过只限于Windows7系统中,所以要调用这段代码,还要检查操作系统的版本要大于6,并且添加对程序集WindowsAPICodePackforMicrosoft?.NETFramework的援用,请到这个地址下载
8检查程序对内存的消耗用下面的方法,可以检查.NET给程序分配的内存数量
longavailable=tTotalMemory(false);iteLine(“Beforeallocations:{0:N0}”,available);intallocSize=;byte[]bigArray=newbyte[allocSize];available=tTotalMemory(false);iteLine(“Afterallocations:{0:N0}”,available);在我的系统中,它运行的结果以下所示
Beforeallocations:,Afterallocations:40,,使用下面的方法,可以检查当前应用程序占用的内存
Processproc=tCurrentProcess();iteLine(“ProcessInfo:“+wLine+“PrivateMemorySize:{0:N0}”+wLine+“VirtualMemorySize:{1:N0}”+wLine+“WorkingSetSize:{2:N0}”+wLine+“PagedMemorySize:{3:N0}”+wLine+“PagedSystemMemorySize:{4:N0}”+wLine+“Non-pagedSystemMemorySize:{5:N0}”+wLine,ivateMemorySize64,rtualMemorySize64,rkingSet64,gedMemorySize64,gedSystemMemorySize64,npagedSystemMemorySize64);9使用记秒表检查程序运行时间如果你耽忧某些代码非常耗费时间,可以用StopWatch来检查这段代码消耗的时间,如下面的代码所示
opwatchtimer=opwatch();art();Decimaltotal=0;intlimit=;for(inti=0;ilimit;++i){total=total+(Decimal)rt(i);}op();iteLine(“Sumofsqrts:{0}”,total);iteLine(“Elapsedmilliseconds:{0}”,apsedMilliseconds);iteLine(“Elapsedtime:{0}”,apsed);现在已有专门的工具来检测程序的运行时间,可以细化到每一个方法,比如dotNetPerformance软件。
以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。
classAutoStopwatch:opwatch,IDisposable{publicAutoStopwatch(){Start();}publicvoidDispose(){Stop();iteLine(“Elapsed:{0}”,apsed);}}借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。
using(newAutoStopwatch()){Decimaltotal2=0;intlimit2=;for(inti=0;ilimit2;++i){total2=total2+(Decimal)rt(i);}}10使用光标当程序正在后台运行保存或是册除操作时,应当将光标状态修改为劳碌。可使用下面的技能。
classAutoWaitCursor:IDisposable{privateControl_target;privateCursor_prevCursor=fault;publicAutoWaitCursor(Controlcontrol){if(control==null){thrownewArgumentNullException(“control”);}_target=control;_prevCursor=_rsor;_rsor=itCursor;}publicvoidDispose(){_rsor=_prevCursor;}}用法以下所示,这个写法,是为了预感到程序可能会抛出异常
using(newAutoWaitCursor(this)){...thrownewException();}如代码所示,即便抛出异常,光标也可以恢复到之间的状态。
北京治疗白癜风的好医院白癜风医院