好的,所以我解决了这个问题。我所做的是几件事:
- 首先,我在域中扫描机器。
- 检查SQLBrowser服务是否正在运行,如果没有,启动它!这是由
ServiceController class
位于system.ServiceProcess
- 启动所有 SQLBrowser 后,我使用
SqlDataSourceEnumerator
枚举所有实例。
对于那些对代码感兴趣的人:
注意:您需要网络管理员权限才能在远程机器上启动它。
public void StartSqlBrowserService(List<String> activeMachines)
{
ServiceController myService = new ServiceController();
myService.ServiceName = "SQLBrowser";
foreach (var machine in activeMachines)
{
try
{
myService.MachineName = machine;
string svcStatus = myService.Status.ToString();
switch (svcStatus)
{
case "ContinuePending":
Console.WriteLine("Service is attempting to continue.");
break;
case "Paused":
Console.WriteLine("Service is paused.");
Console.WriteLine("Attempting to continue the service.");
myService.Continue();
break;
case "PausePending":
Console.WriteLine("Service is pausing.");
Thread.Sleep(5000);
try
{
Console.WriteLine("Attempting to continue the service.");
myService.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
break;
case "Running":
Console.WriteLine("Service is already running.");
break;
case "StartPending":
Console.WriteLine("Service is starting.");
break;
case "Stopped":
Console.WriteLine("Service is stopped.");
Console.WriteLine("Attempting to start service.");
myService.Start();
break;
case "StopPending":
Console.WriteLine("Service is stopping.");
Thread.Sleep(5000);
try
{
Console.WriteLine("Attempting to restart service.");
myService.Start();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
break;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
然后这就是我用来检索实例的方法。
public static void SqlTestInfo()
{
SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance;
DataTable table = instance.GetDataSources();
DisplayData(table);
}
private static void DisplayData(DataTable table)
{
foreach (DataRow row in table.Rows)
{
foreach (DataColumn dataColumn in table.Columns)
{
Console.WriteLine("{0} = {1}", dataColumn.ColumnName, row[dataColumn]);
}
Console.WriteLine();
}
}
它可能不是最好的解决方案,有些人可能会觉得它有点脏。但就目前而言,这是我能得到的最好的解决方法。
希望这可以帮助将来遇到同样问题的任何人。