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 Microsoft®.NET Framework的援用,请到这个地点下载 http://www.ki4.cn/
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(); }
如代码所示,纵然抛出非常,光标也能够恢复到之间的状况。
以上就是C#顺序员经常用到的10个有用代码片断细致引见的细致内容,更多请关注ki4网别的相干文章!