[转载].NET开发常用的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提供的实用功能常常用来管理应用程序中的服务,而不必到控制面板的管理服务中进行操作。
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}\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://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 );
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();
}
如代码所示,即使抛出异常,光标也可以恢复到之间的状态。
博客转自:JamesLi的《C#程序开发中经常遇到的10条实用的代码》
[转载].NET开发常用的10条实用代码的更多相关文章
- web前端开发常用的10个高端CSS UI开源框架
web前端开发常用的10个高端CSS UI开源框架 随着人们对体验的极致追求,web页面设计也面临着新的挑战,不仅需要更人性化的设计理念,还需要设计出更酷炫的页面.作为web前端开发人员,运用开源 ...
- C#程序开发中经常遇到的10条实用的代码
1 读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine("Platform: ...
- (转)C#程序开发中经常遇到的10条实用的代码
原文地址:http://www.cnblogs.com/JamesLi2015/p/3147986.html 1 读取操作系统和CLR的版本 OperatingSystem os = System.E ...
- Java 后端开发常用的 10 种第三方服务
请肆无忌惮地点赞吧,微信搜索[沉默王二]关注这个在九朝古都洛阳苟且偷生的程序员.本文 GitHub github.com/itwanger 已收录,里面还有我精心为你准备的一线大厂面试题. 严格意义上 ...
- 提升开发幸福感的10条JS技巧
鱼头总结一些能够提高开发效率的JS技巧,这些技巧很实用,觉得挺好,想推荐给大家,所以有了这篇文章. 生成随机UID const genUid = () => { var length = 20 ...
- [转载]Android开发常用调试技术记录
ANDROID 调试技术: 1)Ps 指令 ls –l /proc/27/ cat /proc/27/cmdline #cmdline文件表示了这个进程所在的命令行. cat /proc/ ...
- C#程序员经常用到的10个实用代码片段 - 操作系统
原文地址 如果你是一个C#程序员,那么本文介绍的10个C#常用代码片段一定会给你带来帮助,从底层的资源操作,到上层的UI应用,这些代码也许能给你的开发节省不少时间.以下是原文: 1 读取操作系统和C ...
- C#程序员经常用到的10个实用代码片段
1 读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion; Console.WriteLine(“Platform: {}”, ...
- VS 2015 开发Android底部导航条----[实例代码,多图]
1.废话背景介绍 在Build 2016开发者大会上,微软宣布,Xamarin将被整合进所有版本的Visual Studio之中. 这也就是说,Xamarin将免费提供给所有购买了Visual ...
随机推荐
- Python小知识点(2)
1.简述Python的运行过程 在说这个问题之前,我们先来说两个概念,PyCodeObject和pyc文件. 我们在硬盘上看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器 ...
- GeoServer之SqlView
GeoServer之SqlView GeoServer中的新建图层中有一个配置新的SQL视图选项,即SqlView功能的入口. SqlView可以利用sql语句在geoserver中直接查询表中的几个 ...
- Please specify exact device preset UUID
Please specify exact device preset UUID 重启RAD IDE,重新选择 IOS Simulator ,iphone 机型!
- Shiro学习之路 -- 架构及其组件
出自:跟我学shiro 简介 Apache Shiro 是 Java 的一个安全框架.目前,使用 Apache Shiro 的人越来越多,因为它相当简单,对比 Spring Security,可能没有 ...
- jena读取和解析本体文件
使用jena开发本体应用程序时,首先需要对我们利用本体构建工具,如protege等,构建的本体文件,如owl.rdf等读取并解析得到本体模型.下面给出相应的代码,不对的地方请指正. (基于jena 2 ...
- Android的SearchView详解
转自https://www.jianshu.com/p/7c1e78e91506 一.简述 SearchView是v7包中的一个兼容性控件,它可以单独使用,也可以配合menu+toolbar一起使用. ...
- C# 对象封装为json格式
1 对象 public class Person { public string Name { get; set; } public int Age { get; set; } public Date ...
- solr自动提示 - jquery ui autocomplete
需求: 搜索框中 输入部分关键词之后,有下拉联想提示.选中提示,使用鼠标或者使用enter键,则触发搜索功能.没有选择搜索提示,使用部分输入关键词作为搜索,直接使用enter键也能触发搜索功能.整个过 ...
- javascript对变量和函数的声明提前‘hoist’
hoist vt.升起,提起; vi.被举起或抬高; n.起重机,升降机; 升起; <俚>推,托,举; 原文地址:http://www.bootcss.com/article/variab ...
- sed高级用法:模式空间(pattern space)和保持空间(hold space)
摘自:https://blog.csdn.net/ITsenlin/article/details/21129405 sed高级用法:模式空间(pattern space)和保持空间(hold spa ...