Monday, September 17, 2007

Starting a service and WMI

[this post came from our old blog]
One of my students asked me how to start/stop a service from .net application. The simple way to do it is using the ServiceController class:

ServiceController sc = new ServiceController();
sc.ServiceName = "Dnscache";
sc.Stop();

Another way is to use WMI
2 ways to do it:
A. Using classes from System.Management namespace
B. Generate .NET proxy class to access WMI class:

Example(B)

1. Using visual studio command prompt type :

C:\demo>mgmtclassgen win32_Service

Microsoft (R) .NET Framework Version 2.0.50727.42
Copyright (C) Microsoft Corporation. All rights reserved.
Generating Code for WMI Class win32_Service ...
Code Generated Successfully!!!!

2. Add the generated file to your project
3. Add reference to system.management.dll
4. Use the class

Service s = new Service(new ManagementPath("\\\\localhost\\root\\cimv2:Win32_Service.Name='Dnscache'"));

s.StartService();
//…….
s.StopService();

WMI helps in many management tasks like installing software, monitoring events etc.
Note that within windows 2003 Server Microsoft added many methods to WMI classes. Using the above tool in windows 2003 server usually generate a bigger class file

for help and other learning materials
visit our site: Bina

No comments: