


Detailed introduction to 10 practical code snippets frequently used by C# programmers
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);
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; }
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); }
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)); } }
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>
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 }); }
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);
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();
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 ://www.php.cn/
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);
In my system, the result of its operation is as follows
Before allocations: 651,064 After allocations: 40,690,080
Use the following method to check the memory occupied 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 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);
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); } }
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); } }
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; } }
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(); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to C# Serialization. Here we discuss the introduction, steps of C# serialization object, working, and example respectively.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.
