Monday, February 06, 2006

Start and Stop Windows Services using Visual Basic 2005

Start and Stop Windows Services using Visual Basic 2005

Different windows services are used to perform different operations on Windows operating system family. These services may include database services, email services or a lot of other. So, while performing automated tasks we need to start and stop these services programmatically. Here, I’ll show you how to perform this task in Visual Basic 2005.

Go to Control Panel and then Administrative Tools and Open Services Tool. Here you can find all the windows services running at your system. For example, you want to stop and start Microsoft SQL Server Service. First of all find out the name of the service from the services tool.
Name of the Microsoft SQL Server Service





















Its name is MSSQLSERVER. We’ll use this name to start and stop the service.

Create a Visual Basic.Net Windows Application project in Visual Studio 2005.
The Namespace we are going to use in this article is System.ServiceProcess.
So, import this namespace in your Visual Basic.Net project. Create an object of ServiceController class of this namespace. While creating this object you’ll have to provide the service name as parameter.


Dim objController As New ServiceController("MSSQLSERVER")

You’ll have to find the status of the service before you stop it. So, check if the status of this service is running then call stop method on this service.

If objController.Status = ServiceControllerStatus.Running Then
objController.Stop()
End If

You can give some delay so that you’ll be able to view the result of these statements.

System.Threading.Thread.Sleep(5000)

Here we have given delay of five seconds. Now, you can start your service again with the Start method of Service controller class.
But remember, check the status again and if the service has already been stopped then start it again otherwise you’ll be caught by an exception.

If objController.Status = ServiceControllerStatus.Stopped Then
objController.Start()
End If

No comments: