10 useful Code Snippets that C # programmers often use

Source: Internet
Author: User

1 read the operating system and CLR version
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 NT 6.1.7600.0
CLR version:4.0.21006.1

2 read the number of CPUs, memory capacity

The required information can be read through the interface provided by 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;}

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 64-bit? {0} ",   Environment.is64bitoperatingsystem); Console.WriteLine ("Is Process 64-bit?") {0} ",  environment.is64bitprocess); Console.WriteLine ("Little-endian: {0}", Bitconverter.islittleendian); foreach (  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 Reading registry key-value pairs
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));}    }

Please add the namespace Microsoft.Win32 to ensure that the above code can be compiled.

4 Start, Stop the 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 = new ServiceController ("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 services

if (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 Verify if 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 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);

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 using new features of Windows7

Windows7 system introduces some new features, such as Open File dialog, status bar can show the progress of the current task.

Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd = new  Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog (); ofd. Addtomostrecentlyusedlist = True;ofd. Isfolderpicker = True;ofd. Allownonfilesystemitems = 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, check the operating system version to be greater than 6, and add a reference to the assembly Windows API Code Pack for microsoft®.net framework. Please go to this address to download Http://code.msdn.microsoft.com/WindowsAPICodePack

8 checking 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 allocsize = 40000000;byte[] Bigarray = new Byte[allocsize ];available = GC. Gettotalmemory (FALSE); Console.WriteLine ("After allocations: {0:n0}", available);

In my system, it runs the result as shown below

Before Allocations:651,064after allocations:40,690,080

Use the following method to check the memory consumed by the current application

"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 using 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 = new System.Diagnostics.Stopwatch (); timer. Start ();D ecimal 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);

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: {0}", this. 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 ()) {    Decimal total2 = 0;    int limit2 = 1000000;    for (int i = 0; i < limit2; ++i)    {       Total2 = Total2 + (Decimal) math.sqrt (i);}    }
10 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.

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;}}

The usage is as follows, in order to anticipate that the program may throw an exception

using (new Autowaitcursor (this)) {... throw new Exception ();}

10 useful Code Snippets that C # programmers often use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.