1 read the operating system and CLR version of
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);
In my Windows 7 system, output the following information
Platform:win32nt
Service Pack:
version:6.1.7600.0
Versionstring:microsoft Windows NT6.1.7600.0
CLR version:4.0.21006.1
2 Read CPU quantity, Memory capacity
The required information can be read through the interface provided by Windowsmanagement Instrumentation (WMI).
Private StaticUInt32 countphysicalprocessors () {ManagementObjectSearcher objects=Newmanagementobjectsearcher ("Select*From Win32_ComputerSystem "); Managementobjectcollection Coll=objects. Get (); foreach(ManagementObject objinchColl) { return(UInt32) obj["NumberOfProcessors"]; } return 0;}Private StaticUInt64 countphysicalmemory () {ManagementObjectSearcher objects=Newmanagementobjectsearcher ("Select*From win32_physicalmemory "); Managementobjectcollection Coll=objects. Get (); UInt64 Total=0; foreach(ManagementObject objinchColl) { Total+=(UInt64) obj["Capacity"]; } returnTotal ;}
Add a reference to assembly System.Management to ensure that your code compiles correctly.
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 --bit? {0} ", Environment.is64bitoperatingsystem); Console.WriteLine ("is Process --bit? {0} ", environment.is64bitprocess); Console.WriteLine ("Little-endian: {0} ", Bitconverter.islittleendian);foreach(Screen screeninchSystem.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 Read registry key value pairs
using (RegistryKey Keyrun = Registry.LocalMachine.OpenSubKey (@ "SOFTWARE\Microsoft\Windows\CurrentVersion\Run")) { foreach (string in keyrun.getvaluenames ()) { Console.WriteLine ("Name: {0}\tvalue: {1}", ValueName, Keyrun.getvalue ( ValueName));} }
Please add the namespace Microsoft.Win32 to ensure that the above code can be compiled.
4 Start, Stop Windows Service
This API provides useful functionality that is often used to manage services in an application without having to operate in the management services of the Control Panel.
ServiceController controller =NewServiceController ("e-m-POWER "); Controller. Start (); if(Controller. CanPauseAndContinue) {controller. Pause (); Controller. Continue (); } controller. Stop (); In the. NET API, you can implement a word of installation and uninstallation servicesif(args[0] ==" /I") {Managedinstallerclass.installhelper (New string[] {assembly.getexecutingassembly (). Location}); } Else if(args[0] =="/ u") {Managedinstallerclass.installhelper (New string[] {"/ u", assembly.getexecutingassembly (). Location}); }
As shown in the code, pass in the I or U parameter to the application to indicate that it is unloading or installing the program.
5 verifies whether the program has Strong Name (P/invoke)
For example, in a program, in order to verify that the assembly has a signature, you can call the following methods
[DllImport ("Mscoree.dll", charset=CharSet.Unicode)]Static extern BOOLStrongNameSignatureVerificationEx (stringwszFilePath,BOOLFforceverification,ref BOOLpfwasverified); BOOLnotforced =false;BOOLVerified = StrongNameSignatureVerificationEx (assembly,false,refnotforced); Console.WriteLine ("verified: {0}\nforced: {1}", verified,!notforced);
This feature is commonly used in software protection methods that can be used to validate signed components. Even if your signature is removed, or if all of the assembly's signatures are removed, you can stop the program from running as long as there is a calling code in the program.
6 responding to changes to system configuration items
For example, when we lock the system, if QQ does not exit, it will show a busy state.
Add the namespace Microsoft.Win32, and then register the following event.
. Displaysettingschanged (includes changing) display settings
. installedfontschanged Font Changes
. Palettechanged
. PowerModeChanged Power state
. sessionended (user is logged out or session ended)
. Sessionswitch (change current user)
. Timechanged Time Change
. UserPreferenceChanged (user bias number includes changing)
Our ERP system will monitor whether the system time changes, if the time adjusted after the ERP license file outside the scope, will cause the ERP software is not available.
7 Use Windows7 the new features
Windows7 system introduces some new features, such as Open File dialog, status bar can show the progress of the current task.
NewTrue True to True; ofd. ShowDialog ();
Open the dialog box in such a way that it has more OpenFileDialog functionality in the BCL's own class library. However, it is limited to Windows 7 systems, so to call this code, also to check the operating system version is greater than 6, and add to the assembly Windows API Code Pack for microsoft®.net framework reference, please go to this address download Http://code.msdn.microsoft.com/WindowsAPICodePack
8 Check the memory consumption of the program
Use the following method to check. Net amount of memory allocated to Programs
long available = GC. Gettotalmemory (false); Console.WriteLine ("Before allocations: {0: N0}", available); int 40000000 ; byte New byte = GC. Gettotalmemory (false); Console.WriteLine ("After allocations: {0: N0}", available);
In my system, it runs the result as shown below
Before allocations:651,064
After allocations:40,690,080
Use the following method to check the memory consumed by the current application
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 Use the stopwatch to check the program run time
If you are concerned that some code is very time consuming, you can use stopwatch to check how long this code consumes, as shown in the following code
System.Diagnostics.Stopwatch timer =NewSystem.Diagnostics.Stopwatch (); timer. Start ();D ecimal Total=0;intLimit =1000000; for(inti =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);
There are now specialized tools to detect the running time of the program, which can be refined to each method, such as the Dotnetperformance software.
In the above code example, you need to modify the source code directly, if it is used to test the program, it is not convenient. Please refer to the example below.
class AutoStopwatch:System.Diagnostics.Stopwatch, idisposable{ public autostopwatch () { Start (); } Public void Dispose () { Stop (); Console.WriteLine ("Elapsed: {0this. Elapsed);} }
With the using syntax, as shown in the following code, you can check the run time of a piece of code and print it on the console.
using (new Autostopwatch ()) { 0; int 1000000 ; for (int0; i < limit2; + +i) { = Total2 + (Decimal) math.sqrt (i);} }
Ten using the cursor
You should modify the cursor state to busy when the program is running in the background or when the book is in addition to the operation. You can use the following tips.
classautowaitcursor:idisposable{PrivateControl _target;PrivateCursor _prevcursor =Cursors.Default; Publicautowaitcursor (Control control) {if(Control = =NULL) { Throw NewArgumentNullException ("control"); } _target=control; _prevcursor=_target. Cursor; _target. Cursor=cursors.waitcursor;} Public voidDispose () {_target. Cursor=_prevcursor;}}
The usage is as follows, in order to anticipate that the program may throw an exception
using (new Autowaitcursor (This))
{
...
throw new Exception ();
}
As the code shows, even if an exception is thrown, the cursor can revert to the state between.
10 useful Code Snippets that C # programmers often use