10 practical code snippets frequently used by C# programmers

伊谢尔伦
Release: 2016-11-30 11:05:53
Original
1215 people have browsed it

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

ServiceController controller = new ServiceController(“e-M-POWER”);      
controller.Start();      
if (controller.CanPauseAndContinue)      
{      
    controller.Pause();      
    controller.Continue();      
}      
controller.Stop();
Copy after login

 In the API provided by .net, you can implement one-sentence 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 });
 }
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 the program, in order to verify whether the assembly has a signature, you can 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);
Copy after login

 This function is often 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. A. DisplaySettingSchanged (including the change) display

. InstalledfontSchanged font changes

. Palettechanged
. SESSIONSWITCH (Change the current user)
. . UserPreferenceChanged (User preference 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 operating system version is greater than 6, and add a reference to the assembly Windows API Code Pack for Microsoft®.NET Framework. Please download it at this address http ://code.msdn.microsoft.com/WindowsAPICodePack

 8 Check the memory consumption of the program

Using the following method, you can 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, it runs The results are as follows

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

Using the following method, you can 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 this section The time consumed by the code, as shown in the code below

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

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 a little 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 code below, 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 Using 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

  用法如下所示,这个写法,是为了预料到程序可能会抛出异常

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

  如代码所示,即使抛出异常,光标也可以恢复到之间的状态。


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