Skip to main content
 首页 » 编程设计

c#之为什么 SQL Server 实例不总是出现在枚举中

2024年02月23日15mfrbuaa

我正在尝试让 SQL Server 实例在我的 PC 上运行。

SqlDataSourceEnumerator instance = SqlDataSourceEnumerator.Instance; 
DataTable table = instance.GetDataSources(); 
foreach (DataRow row in table.Rows) 
{ 
   SqlInstanceCollection.Items.Add(row["ServerName"].ToString() + "\\" + row["InstanceName"].ToString()); 
   SqlInstanceCollection.Text = SqlInstanceCollection.Items[0].ToString(); 
} 

我面临的问题是,有时我会获得实例,而有时却没有,即使服务器正在运行也是如此。

获取正在运行的 SQL Server 的实例列表需要多长时间?

任何帮助将不胜感激。

请您参考如下方法:

来自 MSDN:

Due to the nature of the mechanism used by SqlDataSourceEnumerator to locate data sources on a network, the method will not always return a complete list of the available servers, and the list might not be the same on every call. If you plan to use this function to let users select a server from a list, make sure that you always also supply an option to type in a name that is not in the list, in case the server enumeration does not return all the available servers. In addition, this method may take a significant amount of time to execute, so be careful about calling it when performance is critical.

SqlDataSourceEnumerator.GetDataSources Method

正如他们的注释中所述,方法在设计上是不可靠的;)奇怪!

编辑:如果我必须解决类似的问题,我会尝试使用具有适当参数集的 Windows API NetServerEnum。这确实不是微不足道的,但应该更可靠。