您的位置:首页 > 编程语言 > C#

C#程序开发中经常遇到的10条实用的代码

2013-06-21 13:08 316 查看


1读取操作系统和CLR的版本

OperatingSystemos=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(“CLRVersion:{0}”,System.Environment.Version);



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

Platform:Win32NT

ServicePack:

Version:6.1.7600.0

VersionString:MicrosoftWindowsNT6.1.7600.0

CLRVersion:4.0.21006.1


2读取CPU数量,内存容量

可以通过WindowsManagementInstrumentation(WMI)提供的接口读取所需要的信息。

privatestaticUInt32CountPhysicalProcessors()
{
ManagementObjectSearcherobjects=newManagementObjectSearcher(
“SELECT*FROMWin32_ComputerSystem”);
ManagementObjectCollectioncoll=objects.Get();
foreach(ManagementObjectobjincoll)
{
return(UInt32)obj[“NumberOfProcessors”];
}
return0;
}
privatestaticUInt64CountPhysicalMemory()
{
ManagementObjectSearcherobjects=newManagementObjectSearcher(
“SELECT*FROMWin32_PhysicalMemory”);
ManagementObjectCollectioncoll=objects.Get();
UInt64total=0;
foreach(ManagementObjectobjincoll)
{
total+=(UInt64)obj[“Capacity”];
}
returntotal;
}


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

Console.WriteLine(“Machine:{0}”,Environment.MachineName);
Console.WriteLine(“#ofprocessors(logical):{0}”,Environment.ProcessorCount);
Console.WriteLine(“#ofprocessors(physical):{0}”CountPhysicalProcessors());
Console.WriteLine(“RAMinstalled:{0:N0}bytes”,CountPhysicalMemory());
Console.WriteLine(“IsOS64-bit?{0}”,Environment.Is64BitOperatingSystem);
Console.WriteLine(“Isprocess64-bit?{0}”,Environment.Is64BitProcess);
Console.WriteLine(“Little-endian:{0}”,BitConverter.IsLittleEndian);
foreach(ScreenscreeninSystem.Windows.Forms.Screen.AllScreens)
{
Console.WriteLine(“Screen{0}”,screen.DeviceName);
Console.WriteLine(“\tPrimary{0}”,screen.Primary);
Console.WriteLine(“\tBounds:{0}”,screen.Bounds);
Console.WriteLine(“\tWorkingArea:{0}”,screen.WorkingArea);
Console.WriteLine(“\tBitsPerPixel:{0}”,screen.BitsPerPixel);
}




3读取注册表键值对

using(RegistryKeykeyRun=Registry.LocalMachine.OpenSubKey(@”Software\Microsoft\Windows\CurrentVersion\Run”))
{
foreach(stringvalueNameinkeyRun.GetValueNames())
{
Console.WriteLine(“Name:{0}\tValue:{1}”,valueName,keyRun.GetValue(valueName));
}
}


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


4启动,停止Windows服务

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

ServiceControllercontroller=newServiceController(“e-M-POWER”);
controller.Start();
if(controller.CanPauseAndContinue)
{
controller.Pause();
controller.Continue();
}
controller.Stop();


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

if(args[0]=="/i")
{
ManagedInstallerClass.InstallHelper(newstring[]{Assembly.GetExecutingAssembly().Location});
}
elseif(args[0]=="/u")
{
ManagedInstallerClass.InstallHelper(newstring[]{"/u",Assembly.GetExecutingAssembly().Location});
}


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


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

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

[DllImport("mscoree.dll",CharSet=CharSet.Unicode)]
staticexternboolStrongNameSignatureVerificationEx(stringwszFilePath,boolfForceVerification,refboolpfWasVerified);

boolnotForced=false;
boolverified=StrongNameSignatureVerificationEx(assembly,false,refnotForced);
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.CommonOpenFileDialogofd=newMicrosoft.WindowsAPICodePack.Dialogs.CommonOpenFileDialog();
ofd.AddToMostRecentlyUsedList=true;
ofd.IsFolderPicker=true;
ofd.AllowNonFileSystemItems=true;
ofd.ShowDialog();



用这样的方法打开对话框,与BCL自带类库中的OpenFileDialog功能更多一些。不过只限于Windows7系统中,所以要调用这段代码,还要检查操作系统的版本要大于6,并且添加对程序集WindowsAPICodePackforMicrosoft®.NETFramework的引用,请到这个地址下载http://code.msdn.microsoft.com/WindowsAPICodePack


8检查程序对内存的消耗

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

longavailable=GC.GetTotalMemory(false);
Console.WriteLine(“Beforeallocations:{0:N0}”,available);
intallocSize=40000000;
byte[]bigArray=newbyte[allocSize];
available=GC.GetTotalMemory(false);
Console.WriteLine(“Afterallocations:{0:N0}”,available);


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

Beforeallocations:651,064
Afterallocations:40,690,080



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

Processproc=Process.GetCurrentProcess();
Console.WriteLine(“ProcessInfo:“+Environment.NewLine+

“PrivateMemorySize:{0:N0}”+Environment.NewLine+
“VirtualMemorySize:{1:N0}”+Environment.NewLine+

“WorkingSetSize:{2:N0}”+Environment.NewLine+
“PagedMemorySize:{3:N0}”+Environment.NewLine+
“PagedSystemMemorySize:{4:N0}”+Environment.NewLine+

“Non-pagedSystemMemorySize:{5:N0}”+Environment.NewLine,
proc.PrivateMemorySize64,proc.VirtualMemorySize64,proc.WorkingSet64,proc.PagedMemorySize64,proc.PagedSystemMemorySize64,proc.NonpagedSystemMemorySize64);




9使用记秒表检查程序运行时间

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

System.Diagnostics.Stopwatchtimer=newSystem.Diagnostics.Stopwatch();
timer.Start();
Decimaltotal=0;
intlimit=1000000;
for(inti=0;i<limit;++i)
{
total=total+(Decimal)Math.Sqrt(i);
}
timer.Stop();
Console.WriteLine(“Sumofsqrts:{0}”,total);
Console.WriteLine(“Elapsedmilliseconds:{0}”,
timer.ElapsedMilliseconds);
Console.WriteLine(“Elapsedtime:{0}”,timer.Elapsed);



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

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

classAutoStopwatch:System.Diagnostics.Stopwatch,IDisposable
{
publicAutoStopwatch()
{
Start();
}
publicvoidDispose()
{
Stop();
Console.WriteLine(“Elapsed:{0}”,this.Elapsed);
}
}


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

using(newAutoStopwatch())
{
Decimaltotal2=0;
intlimit2=1000000;
for(inti=0;i<limit2;++i)
{
total2=total2+(Decimal)Math.Sqrt(i);
}
}





10使用光标

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

classAutoWaitCursor:IDisposable
{
privateControl_target;
privateCursor_prevCursor=Cursors.Default;
publicAutoWaitCursor(Controlcontrol)
{
if(control==null)
{
thrownewArgumentNullException(“control”);
}
_target=control;
_prevCursor=_target.Cursor;
_target.Cursor=Cursors.WaitCursor;
}
publicvoidDispose()
{
_target.Cursor=_prevCursor;
}
}



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

using(newAutoWaitCursor(this))
{
...
thrownewException();
}


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

原文地址:http://www.cnblogs.com/JamesLi2015/p/3147986.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: