Home > Backend Development > C#.Net Tutorial > Detailed introduction to 10 practical code snippets frequently used by C# programmers

Detailed introduction to 10 practical code snippets frequently used by C# programmers

黄舟
Release: 2017-03-09 15:40:14
Original
1303 people have browsed it

10 practical code snippets often used by C# programmers are introduced in detail:

1 Read the version of the operating system and 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);
Copy after login

​In my Windows 7 system, the following information is output

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 and 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;
}
Copy after login

Please add a reference to the assembly System.Management to ensure that the code can be compiled 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 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);
}
Copy after login

3. Read the registry key-value pair

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));
    }
}
Copy after login

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

4 Start and stop Windows services

The practical functions provided by this API are often used to manage services in applications without having to go to the management services of the control panel.

<p style="margin-bottom: 7px;">ServiceController controller = new ServiceController(“e-M-POWER”);      <br/>controller.Start();      <br/>if (controller.CanPauseAndContinue)      <br/>{      <br/>    controller.Pause();      <br/>    controller.Continue();      <br/>}      <br/>controller.Stop();<br/></p>
Copy after login

In the API provided by .net, you can install and uninstall services in one sentence

 if (args[0] == "/i")
 {
       ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
 }
 else if (args[0] == "/u")
 {
   ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
 }
Copy after login

As shown in the code, pass the i or u parameter to the application to indicate whether to uninstall or install the program.

5. Verify whether the program has a strong name (P/Invoke)

For example, in a program, in order to verify whether the assembly is signed, the following method can be called

[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);
Copy after login

This function is commonly used in software protection methods and can be used to verify signed components. Even if your signature is removed, or the signatures of all assemblies are removed, as long as there is this calling code in the program, the program can be stopped from running.

6. Respond to changes in system configuration items

For example, after we lock the system, if QQ does not exit, it will show a busy status.

Please add the namespace Microsoft.Win32, and then register the following events.

. DisplaySettingsChanged (including Changing) Display Settings
. InstalledFontsChanged Font changes
.PaletteChanged
. PowerModeChanged power status
.SessionEnded (The user is logging out or the session has ended)
.SessionSwitch (Change current user)
. TimeChanged Time change
. UserPreferenceChanged (user preference number includes Changing)

Our ERP system will monitor whether the system time has changed. If the time is adjusted outside the range of the ERP license file, the ERP software will become unavailable.

7. Use the new features of Windows 7

The Windows 7 system introduces some new features, such as the Open File dialog box, and the status bar can display 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();
Copy after login

Using this method to open a dialog box has more functions than the OpenFileDialog in BCL's own class library. However, it is limited to Windows 7 systems, so to call this code, you must also check that the version of the operating system is 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 ://m.sbmmt.com/

8 Check the memory consumption of the program

Use the following method to check the amount of memory allocated by .NET to the program

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);
Copy after login

​In my system, the result of its operation is as follows

Before allocations: 651,064
After allocations: 40,690,080
Copy after login

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

Process proc = Process.GetCurrentProcess();
Console.WriteLine(“Process Info: “+Environment.NewLine+
Copy after login
 “Private Memory Size: {0:N0}”+Environment.NewLine +
“Virtual Memory Size: {1:N0}” + Environment.NewLine +
Copy after login
“Working Set Size: {2:N0}” + Environment.NewLine +
“Paged Memory Size: {3:N0}” + Environment.NewLine +
“Paged System Memory Size: {4:N0}” + Environment.NewLine +
Copy after login
  “Non-paged System Memory Size: {5:N0}” + Environment.NewLine,
proc.PrivateMemorySize64,   proc.VirtualMemorySize64,  proc.WorkingSet64,  
proc.PagedMemorySize64, proc.PagedSystemMemorySize64,  proc.NonpagedSystemMemorySize64 );
Copy after login

9 Use a stopwatch to check the program running time

If you are worried that some code is very time-consuming, you can use StopWatch to check the time consumed by this code, as shown in the following code

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);
Copy after login

Now there are special tools to detect the running time of the program, which can be refined to each method, such as dotNetPerformance software.

Taking the above code as an example, you need to modify the source code directly, which is somewhat inconvenient if it is used to test the program. 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);
   }
}
Copy after login

With the help of using syntax, as shown in the following code, you can check the running 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);
    }
}
Copy after login

10 Use the cursor

When the program is running a save or delete operation in the background, the cursor status should be changed to busy. 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;
}
}
Copy after login

The usage is as follows. This way of writing is to anticipate that the program may throw an exception

using (new AutoWaitCursor(this))
{
...
throw new Exception();
}
Copy after login

As shown in the code, even if an exception is thrown, the cursor can be restored to the previous state.

The above is the detailed content of Detailed introduction to 10 practical code snippets frequently used by C# programmers. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template