当前位置: 首页 > 科技观察

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

时间:2023-03-13 22:24:23 科技观察

1读取操作系统和CLR版本:{0}",os.ServicePack);Console.WriteLine("版本:{0}",os.Version);Console.WriteLine("VersionString:{0}",os.VersionString);Console.WriteLine(“CLRVersion:{0}”,System.Environment.Version);在我的Windows7系统中,输出如下信息Platform:Win32NTServicePack:Version:6.1.7600.0VersionString:MicrosoftWindowsNT6.1.7600.0CLRVersion:4.0.21006.12要读取CPU数量和内存容量,可以通过接口读取需要的信息由WindowsManagementInstrumentation(WMI)提供。privatestaticUInt32CountPhysicalProcessors(){ManagementObjectSearcherobjects=newManagementObjectSearcher(“SELECT*FROMWin32_ComputerSystem”);ManagementObjectCollectioncoll=objects.Get();foreach(ManagementObjectobjincoll){return(UInt32)obj[“NumberOfProcessors”];}return0;}privatestaticUInt64CountPhysicalMemorySearment()("SELECT*FROMWin32_PhysicalMemory");ManagementObjectCollectioncoll=objects.Get();UInt64total=0;foreach(ManagementObjectobjincoll){total+=(UInt64)obj["Capacity"];}returntotal;}请添加对程序集System.ManagementReferences的引用以确保代码正确编译。Console.WriteLine(“机器:{0}”,Environment.MachineName);Console.WriteLine(“#ofprocessors(logical):{0}”,Environment.ProcessorCount);Console.WriteLine(“#ofprocessors(physical):{0}”CountPhysicalProcessors());Console.WriteLine(“RAMinstalled:{0:N0}bytes”,CountPhysicalMemory());Console.WriteLine(“IsOS64-bit?{0}”,Environment.Is64BitOperatingSystem);Console.WriteLine(“Isprocess64-bit?{0}”,Environment.Is64BitProcess);Console.WriteLine(“Little-endian:{0}”,BitConverter.IsLittleEndian);foreach(ScreenscreeninSystem.Windows.Forms.Screen.AllScreens){控制台。WriteLine(“Screen{0}”,screen.DeviceName);Console.WriteLine(“\tPrimary{0}”,screen.Primary);Console.WriteLine(“\tBounds:{0}”,screen.Bounds);控制台.WriteLine(“\tWorkingArea:{0}”,screen.WorkingArea);Console.WriteLine(“\tBitsPerPixel:{0}”,screen.BitsPerPixel);}3读取注册表键值对使用(RegistryKeykeyRun=Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”)){foreach(stringvalueNameinkeyRun.GetValueNames()){Console.WriteLine(“名称:{0}\tValue:{1}",valueName,keyRun.GetValue(valueName));}}请添加命名空间Microsoft.Win32,确保以上代码可以编译服务,无需去控制面板的管理服务中操作。ServiceControllercontroller=newServiceController(“e-M-POWER”);controller.Start();if(controller.CanPauseAndContinue){controller.Pause();controller.Continue();}controller.Stop();在.net提供的API中,一-一句安装卸载服务可以执行if(args[0]==”/i”){ManagedInstallerClass.InstallHelper(newstring[]{Assembly.GetExecutingAssembly().Location});}elseif(args[0]==”/u"){ManagedInstallerClass.InstallHelper(newstring[]{"/u",Assembly.GetExecutingAssembly().Location});}如代码所示,将i或u参数传递给应用程序以指示吃了是卸载还是安装。#p#5验证程序是否具有强名称(P/Invoke)。比如在程序中,为了验证程序集是否有签名,可以调用下面的方法[DllImport("mscoree.dll",CharSet=CharSet.Unicode)]staticexternboolStrongNameSignatureVerificationEx(stringwszFilePath,boolfForceVerification,refboolpfWasVerified);boolnotForced=false;boolverified=StrongNameSignatureVerificationEx(assembly,false,refnotForced);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.CommonOpenFileDialogofd=newMicrosoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();ofd.AddToMostRecentlyUsedList=true;ofd.IsFolderPicker=true;ofd.AllowNonFileSystemItems=true;ofd.ShowDialog();  用这个方法打开在BCL自带的类库中dialogbox的功能比OpenFileDialog多。但仅限于Windows7系统,所以要调用这段代码,还必须检查操作系统版本是否大于6,并添加对程序集WindowsAPICodePackforMicrosoft?.NETFramework的引用,请到这个地址下载http://code.msdn.microsoft.com/WindowsAPICodePack8查看程序的内存消耗用下面的方法可以查看.NET分配给程序的内存量longavailable=GC.GetTotalMemory(false);Console.WriteLine(“Beforeallocations:{0:N0}”,available);intallocSize=40000000;byte[]bigArray=newbyte[allocSize];available=GC.GetTotalMemory(false);Console.WriteLine("Afterallocations:{0:N0}",available);在我的系统中,其运行结果如下Beforeallocations:651,064Afterallocations:40,690,080使用如下方法查看当前应用程序占用的内存Processproc=Process.GetCurrentProcess();Console.WriteLine("ProcessInfo:"+Environment.NewLine+"PrivateMemorySize:{0:N0}"+Environment.NewLine+"VirtualMemorySize:{1:N0}"+Environment.NewLine+"WorkingSetSize:{2:N0}"+Environment.NewLine+"PagedMemorySize:{3:N0}"+环境。NewLine+“PagedSystemMemorySize:{4:N0}”+Environment.NewLine+"Non-pagedSystemMemorySize:{5:N0}"+Environment.NewLine,proc.PrivateMemorySize64,proc.VirtualMemorySize64,proc.WorkingSet64,proc.PagedMemorySize64,proc.PagedSystemMemorySize64,proc.NonpagedSystemMemorySize64);如果担心某些代码非常耗时,可以使用StopWatch查看这段代码消耗的时间,如下代码System.Diagnostics.Stopwatchtimer=newSystem.Diagnostics.Stopwatch();timer.Start();Decimaltotal=0;intlimit=1000000;for(inti=0;i