我试图通过带有SMO的c#中的代码启动和停止MS SQL Server 2014(12.0.4487.0)。我用过这个: Starting SQL Server via C# 还有这个 : https://technet.microsoft.com/en-us/library/ms162139%28v=sql.90%29.aspx 它们几乎相同 - 一个在c#中,另一个在VB.NET中。
我的代码:
using Microsoft.SqlServer.Management.Smo.Wmi;
using System;
namespace TEST___SQL_Server
{
class Program
{
static void Main(string[] args)
{
SQLStart.StartSQLService();
Console.ReadLine();
}
}
static class SQLStart
{
public static void StartSQLService()
{
//Declare and create an instance of the ManagedComputer object that represents the WMI Provider services.
ManagedComputer mc = default(ManagedComputer);
mc = new ManagedComputer();
//Iterate through each service registered with the WMI Provider.
Service svc = default(Service);
foreach (Service s in mc.Services)
{
Console.WriteLine(s.Name);
}
//Reference the Microsoft SQL Server service.
svc = mc.Services[0]; // this is my MSSQLSERVER service
//Stop the service if it is running and report on the status continuously until it has stopped.
if (svc.ServiceState != ServiceState.Running)
{
//Start the service and report on the status continuously until it has started.
svc.Start();
while (!(string.Format("{0}", svc.ServiceState) == "Running"))
{
Console.WriteLine(string.Format("{0}", svc.ServiceState));
svc.Refresh();
}
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
svc.Stop();
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
while (!(string.Format("{0}", svc.ServiceState) == "Stopped"))
{
Console.WriteLine(string.Format("{0}", svc.ServiceState));
svc.Refresh();
}
Console.WriteLine(string.Format("{0} service state is {1}", svc.Name, svc.ServiceState));
}
else
{
Console.WriteLine("SQL Server service is not running.");
}
}
}
}
我没有得到它但是当我在我的代码中svc.Start();
启动SQL Server服务(有意且最初停止)时,没有任何事情发生。我一直接受服务停止的状态,从我的角度来看似乎没有发生任何事情。
我错过了什么,或者这个SMO根本不工作? 感谢