C#程序员经常用到的10个实用代码片段
作者:网络转载 发布时间:[ 2015/11/12 14:57:35 ] 推荐标签:测试开发技术 程序员
如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间。以下是原文:
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(“ Primary {0}”, screen.Primary);
Console.WriteLine(“ Bounds: {0}”, screen.Bounds);
Console.WriteLine(“ Working Area: {0}”,screen.WorkingArea);
Console.WriteLine(“ BitsPerPixel: {0}”,screen.BitsPerPixel);
}
3 读取注册表键值对
using (RegistryKey keyRun = Registry.LocalMachine.OpenSubKey(@”SoftwareMicrosoftWindowsCurrentVersionRun”))
{
foreach (string valueName in keyRun.GetValueNames())
{
Console.WriteLine(“Name: {0} Value: {1}”, valueName, keyRun.GetValue(valueName));
}
}
请添加命名空间Microsoft.Win32,以确保上面的代码可以编译。
4 启动,停止Windows服务
这项API提供的实用功能常常用来管理应用程序中的服务,而不必到控制面板的管理服务中进行操作。
ServiceController controller = new ServiceController(“e-M-POWER”);
controller.Start();
if (controller.CanPauseAndContinue)
{
controller.Pause();
controller.Continue();
}
controller.Stop();
.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}
Forced: {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://code.msdn.microsoft.com/WindowsAPICodePack
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 );
相关推荐
更新发布
功能测试和接口测试的区别
2023/3/23 14:23:39如何写好测试用例文档
2023/3/22 16:17:39常用的选择回归测试的方式有哪些?
2022/6/14 16:14:27测试流程中需要重点把关几个过程?
2021/10/18 15:37:44性能测试的七种方法
2021/9/17 15:19:29全链路压测优化思路
2021/9/14 15:42:25性能测试流程浅谈
2021/5/28 17:25:47常见的APP性能测试指标
2021/5/8 17:01:11