目錄
1 读取操作系统和CLR的版本
首頁 後端開發 C#.Net教程 C#程式設計師常用到的10個實用程式碼片段詳細介紹

C#程式設計師常用到的10個實用程式碼片段詳細介紹

Mar 09, 2017 pm 03:40 PM

  C#程序员经常用到的10个实用代码片段详细介绍:

1 读取操作系统和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);
登入後複製

  在我的Windows 7系统中,输出以下信息

  Platform: Win32NT
  Service Pack:
  Version: 6.1.7600.0
  VersionString: Microsoft Windows NT 6.1.7600.0
  CLR Version: 4.0.21006.1

  2 读取CPU数量,内存容量

  可以通过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;
}
登入後複製

  请添加对程序集System.Management的引用,确保代码可以正确编译。

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 读取注册表键值对

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));
    }
}
登入後複製

  请添加命名空间Microsoft.Win32,以确保上面的代码可以编译。

  4 启动,停止Windows服务

  这项API提供的实用功能常常用来管理应用程序中的服务,而不必到控制面板的管理服务中进行操作。

<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>
登入後複製

  .net提供的API中,可以实现一句话安装与卸载服务

 if (args[0] == "/i")
 {
       ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
 }
 else if (args[0] == "/u")
 {
   ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
 }
登入後複製

  如代码所示,给应用程序传入i或u参数,以表示是卸载或是安装程序。

  5 验证程序是否有strong name (P/Invoke)

  比如在程序中,为了验证程序集是否有签名,可调用如下方法

[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);
登入後複製

  这个功能常用在软件保护方法,可用来验证签名的组件。即使你的签名被人去掉,或是所有程序集的签名都被去除,只要程序中有这一项调用代码,则可以停止程序运行。

  6 响应系统配置项的变更

  比如我们锁定系统后,如果QQ没有退出,则它会显示了忙碌状态。

  请添加命名空间Microsoft.Win32,然后对注册下面的事件。

  . DisplaySettingsChanged (包含Changing) 显示设置
  . InstalledFontsChanged 字体变化
  . PaletteChanged
  . PowerModeChanged 电源状态
  . SessionEnded (用户正在登出或是会话结束)
  . SessionSwitch (变更当前用户)
  . TimeChanged 时间改变
  . UserPreferenceChanged (用户偏号 包含Changing)

  我们的ERP系统,会监测系统时间是否改变,如果将时间调整后ERP许可文件之外的范围,会导致ERP软件不可用。

  7 运用Windows7的新特性

  Windows7系统引入一些新特性,比如打开文件对话框,状态栏可显示当前任务的进度。

Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog ofd = new  Microsoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
ofd.AddToMostRecentlyUsedList = true;
ofd.IsFolderPicker = true;
ofd.AllowNonFileSystemItems = true;
ofd.ShowDialog();
登入後複製

  用这样的方法打开对话框,与BCL自带类库中的OpenFileDialog功能更多一些。不过只限于Windows 7系统中,所以要调用这段代码,还要检查操作系统的版本要大于6,并且添加对程序集Windows API Code Pack for Microsoft®.NET Framework的引用,请到这个地址下载 http://www.php.cn/

  8 检查程序对内存的消耗

  用下面的方法,可以检查.NET给程序分配的内存数量

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);
登入後複製

  在我的系统中,它运行的结果如下所示

Before allocations: 651,064
After allocations: 40,690,080
登入後複製

  使用下面的方法,可以检查当前应用程序占用的内存

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 使用记秒表检查程序运行时间

  如果你担忧某些代码非常耗费时间,可以用StopWatch来检查这段代码消耗的时间,如下面的代码所示

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);
登入後複製

  现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。

  以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。

class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
{
   public AutoStopwatch()
   { 
       Start();
   }
   public void Dispose()
   {
       Stop();
       Console.WriteLine(“Elapsed: {0}”, this.Elapsed);
   }
}
登入後複製

  借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。

using (new AutoStopwatch())
{
    Decimal total2 = 0;
    int limit2 = 1000000;
    for (int i = 0; i < limit2; ++i)
    {
       total2 = total2 + (Decimal)Math.Sqrt(i);
    }
}
登入後複製

  10 使用光标

  当程序正在后台运行保存或是册除操作时,应当将光标状态修改为忙碌。可使用下面的技巧。

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;
}
}
登入後複製

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

using (new AutoWaitCursor(this))
{
...
throw new Exception();
}
登入後複製

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

以上是C#程式設計師常用到的10個實用程式碼片段詳細介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

使用 C# 的活動目錄 使用 C# 的活動目錄 Sep 03, 2024 pm 03:33 PM

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

C# 序列化 C# 序列化 Sep 03, 2024 pm 03:30 PM

C# 序列化指南。這裡我們分別討論C#序列化物件的介紹、步驟、工作原理和範例。

C# 中的隨機數產生器 C# 中的隨機數產生器 Sep 03, 2024 pm 03:34 PM

C# 隨機數產生器指南。在這裡,我們討論隨機數產生器的工作原理、偽隨機數和安全數的概念。

C# 資料網格視圖 C# 資料網格視圖 Sep 03, 2024 pm 03:32 PM

C# 資料網格視圖指南。在這裡,我們討論如何從 SQL 資料庫或 Excel 檔案載入和匯出資料網格視圖的範例。

C# 中的模式 C# 中的模式 Sep 03, 2024 pm 03:33 PM

C# 模式指南。在這裡,我們討論 C# 中模式的介紹和前 3 種類型,以及其範例和程式碼實作。

C# 中的階乘 C# 中的階乘 Sep 03, 2024 pm 03:34 PM

C# 階乘指南。這裡我們討論 C# 中階乘的介紹以及不同的範例和程式碼實作。

C# 中的質數 C# 中的質數 Sep 03, 2024 pm 03:35 PM

C# 質數指南。這裡我們討論c#中素數的介紹和範例以及程式碼實作。

c#多線程和異步的區別 c#多線程和異步的區別 Apr 03, 2025 pm 02:57 PM

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。

See all articles