MG. MG. - 7 months ago 30
Vb.net Question

How to restart a service with VB.NET?

Ok, so I'm new to VB.NET and trying to write a program that prompts the user for a server name and then restarts the IIS on that machine.

Problem 1) namespace

System.ServiceProcess
is not being recognized.

Problem 2) need help with code, passing servername into sub.

Imports System
Imports System.ServiceProcess
Imports System.IO
Imports System.Threading

Class RestartIIS
Shared Sub Main()
Run()
End Sub

Public Sub Run()
Console.WriteLine("Please enter the Server Name: ")
Dim ServerName As String = Console.ReadLine()

Dim sc As ServiceController = New ServiceController("W3SVC")

sc.Stop()
Thread.Sleep(2000)
sc.Start()

Console.Write("Press Enter to Exit")
Console.ReadLine()
End Sub
End Class

Answer

You should add a reference to System.ServiceProcess assembly by right clicking the project and clicking Add Reference... and get command line arguments passed to the Main method like this:

Imports System
Imports System.ServiceProcess
Imports System.IO
Imports System.Threading

Class RestartIIS
    Shared Sub Main(ByVal commandLineArgs() as String)
        Run(commandLineArgs(0))
    End Sub

    Public Sub Run(ByVal machineName as String)
        Console.WriteLine("Please enter the Server Name: ")
        Dim ServerName As String = Console.ReadLine()

        Dim sc As ServiceController = New ServiceController("W3SVC", machineName)

        sc.Stop()
        Thread.Sleep(2000)
        sc.Start()

        Console.Write("Press Enter to Exit")
        Console.ReadLine()
    End Sub
End Class