在.net中提供了一些类来显示和管制Windows零碎上的服务,并能够实现对近程计算机服务服务的拜访,如System.ServiceProcess命名空间上面的ServiceController 类,System.Management上面的一些WMI操作的类。尽管用ServiceController能够很不便的实现对服务的管制,而且很直观、简洁和容易了解。然而我认为他的性能同通过WMI来操作服务相比,那可能就有些繁多了,并且对多个服务的操作可能就比拟麻烦,也无奈列出零碎中的所有服务的具体数据。这里要讲的就是如何应用System.Management组件来操作近程和本地计算机上的服务。
WMI作为Windows 2000操作系统的一部分提供了可伸缩的,可扩大的治理架构.公共信息模型(CIM)是由分布式治理工作规范协会(DMTF)设计的一种可扩大的、面向对象的架构,用于管理系统、网络、应用程序、数据库和设施。Windows治理标准也称作CIM for Windows,提供了对立的拜访治理信息的形式。如果须要获取具体的WMI信息请读者查阅MSDN。System.Management组件提供对大量治理信息和治理事件汇合的拜访,这些信息和事件是与依据 Windows 治理标准 (WMI) 构造对系统、设施和应用程序设置检测点无关的。
然而站长博客下面并不是咱们最关怀的,上面才是咱们须要谈的话题。
毫无疑问,咱们要援用System.Management.Dll程序集,并要应用System.Management命名空间下的类,如ManagementClass,ManagementObject等。上面用一个名为Win32ServiceManager的类把服务的一些相干操作包装了一下,代码如下:
using System;
using System.Management;
namespace ZZ.Wmi
{
public class Win32ServiceManager
{
private string strPath;
private ManagementClass managementClass;
public Win32ServiceManager():this(".",null,null)
{
}
public Win32ServiceManager(string host,string userName,string password)
{
this.strPath = "\\"+host+"\root\cimv2:Win32_Service";
this.managementClass = new ManagementClass(strPath);
if(userName!=null&&userName.Length>0)
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = userName;
connectionOptions.Password = password;
ManagementScope managementScope = new ManagementScope( "\\" +host+ "\root\cimv2",connectionOptions) ;
this.managementClass.Scope = managementScope;
}
}
// 验证是否能连贯到近程计算机
public static bool RemoteConnectValidate(string host,string userName,string password)
{
ConnectionOptions connectionOptions = new ConnectionOptions();
connectionOptions.Username = userName;
connectionOptions.Password = password;
ManagementScope managementScope = new ManagementScope( "\\" +host+ "\root\cimv2",connectionOptions) ;
try
{
managementScope.Connect();
}