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

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

时间:2023-03-15 20:39:07 科技观察

如果你是C#程序员,那么本文介绍的10个C#常用代码片段一定能帮到你,从底层的资源操作到上层的UI应用,这些代码可以为您节省大量开发时间。以下为原文:1读取操作系统和CLR的版本OperatingSystemos=System.Environment.OSVersion;Console.WriteLine(“Platform:{0}”,os.Platform);Console.WriteLine(“ServicePack:{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可以通过WindowsManagementInstrumentation(WMI)提供的接口读取CPU数量和内存容量)读取所需的信息。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参数传递给应用程序以指示吃了是卸载还是安装。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(包括更改)显示设置。InstalledFontsChanged字体更改。调色板已更改。PowerModeChanged电源状态。SessionEnded(用户正在注销或会话结束)。我们的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自带的类库中的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);在我的系统中,其运行结果如下分配前:651,064分配后: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}"+环境。换行符+"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