Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the practical code snippets often used by C # programmers

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces the practical code snippets that C # programmers often use for reference, which can be used for reference by interested friends. I hope you will gain a lot after reading this article. Let's take a look at it.

1 read the version of the operating system and CLR

OperatingSystem os = System.Environment.OSVersion; Console.WriteLine ("Platform: {0}", os.Platform); Console.WriteLine ("ServicePack: {0}", os.ServicePack); Console.WriteLine ("Version: {0}", os.Version); Console.WriteLine ("VersionString: {0}", os.VersionString); Console.WriteLine ("CLR Version: {0}", System.Environment.Version)

On 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 number of read CPU, 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 the assembly System.Management to ensure that the 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 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 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 the Windows service

The utility provided by this API 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 API provided by .net, you can implement the one-sentence installation and uninstallation service.

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 an I or u parameter to the application to indicate whether to uninstall or install the program.

5 whether the verifier has strong name (P/Invoke)

For example, in a program, to verify that the assembly is signed, call the following method

[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 and can be used to verify signed components. Even if your signature is removed, or all assembly signatures are removed, as long as there is this calling code in the program, you can stop the program from running.

6 respond to changes in system configuration items

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

Add the namespace Microsoft.Win32, and then register the following event.

. DisplaySettingsChanged (including Changing) display settings. InstalledFontsChanged font changes. PaletteChanged. PowerModeChanged power status. SessionEnded (the user is logging out or the session ends). SessionSwitch (change the current user). TimeChanged time change. UserPreferenceChanged (user bias includes Changing)

Our ERP system will monitor whether the system time has changed. If the time is adjusted outside the scope of the ERP license file, the ERP software will not be available.

7 using the new features of Windows7

The Windows7 system introduces some new features, such as opening a file dialog box, and the status bar shows 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 this way and have more functions with OpenFileDialog in BCL's native class library. However, it is limited to Windows 7 systems, so to call this code, 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 download http://code.msdn.microsoft.com/WindowsAPICodePack from this address

8 check the memory consumption of the program

You can check the amount of memory that .NET allocates to the program in the following way

Long available = GC.GetTotalMemory (false); Console.WriteLine ("Before allocations: {0:N0}", available); int allocSize = 4000000; 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: 651064 After allocations: 40690080

Using the following method, you can check the memory consumed by the current application

Process proc = Process.GetCurrentProcess () Console.WriteLine ("Process Info:" + Environment.NewLine+ "PrivateMemorySize: {0:N0}" + Environment.NewLine+ "VirtualMemorySize: {1:N0}" + Environment.NewLine+ "Working Set Size: {2:N0}" + Environment.NewLine+ "Paged MemorySize: {3:N0}" + Environment.NewLine+ "Paged System MemorySize: {4:N0}" + Environment.NewLine+ "Non-paged System MemorySize: {5:N0}" + Environment.NewLine, proc.PrivateMemorySize64, proc.VirtualMemorySize64 Proc.WorkingSet64, proc.PagedMemorySize64, proc.PagedSystemMemorySize64, proc.NonpagedSystemMemorySize64)

9 check the running time of the program using a stopwatch

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)

There are now 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 following example.

Class AutoStopwatch: System.Diagnostics.Stopwatch, IDisposable {public AutoStopwatch () {Start ();} public void Dispose () {Stop (); Console.WriteLine ("Elapsed: {0}", this.Elapsed);}}

With the help of 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 use the cursor

When the program is running a save or delete operation in the background, you should change the cursor state to busy. The following techniques can be used.

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, and this is written in anticipation that the program may throw an exception

Using (new AutoWaitCursor (this)) {... Throw new Exception ();}

As the code shows, the cursor can return to the state in between even if an exception is thrown.

Thank you for reading this article carefully. I hope the article "what are the practical code snippets often used by C # programmers" shared by the editor will be helpful to everyone? at the same time, I also hope that you will support and pay attention to the industry information channel. more related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report