如何使用 VB.NET 重新启动服务?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/637957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to restart a service with VB.NET?
提问by MG.
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.
好的,所以我是 VB.NET 的新手,并试图编写一个程序,提示用户输入服务器名称,然后在该机器上重新启动 IIS。
Problem 1) namespace System.ServiceProcess
is not being recognized.
Problem 2) need help with code, passing servername into sub.
问题 1) 命名空间System.ServiceProcess
未被识别。
问题 2) 需要代码帮助,将 servername 传递给 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
回答by Mehrdad Afshari
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:
您应该System.ServiceProcess
通过右键单击项目并单击“添加引用...”来添加对程序集的引用,并Main
像这样获取传递给方法的命令行参数:
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
回答by guest
ServiceControl.Stop()
Do
ServiceControl.Refresh()
If ServiceControl.Status = ServiceControllerStatus.Stopped Then
ServiceControl.Start()
Exit Do
End If
Loop