有必要收入Bolg:
1
int i;
2
int _count;
3
4
try
5
{
6
this.Cursor = Cursors.WaitCursor;
7
//Unmanaged SQLDMO call to retrieve the existing SQL Servers
8
object oNames;
9
Type SQLDMOApplication = Type.GetTypeFromProgID("SQLDMO.Application");
10
object oSQLApp = Activator.CreateInstance(SQLDMOApplication);
11
12
//If oSQLApp is null, then SQLDMO.DLL wasn't found installed to the system
13
if (oSQLApp == null)
14
{
15
MessageBox.Show("SQL Data Model Objects assembly not found.");
16
return;
17
}
18
19
//Get Available SQL Servers
20
oNames = oSQLApp.GetType().InvokeMember("ListAvailableSQLServers", BindingFlags.IgnoreCase | BindingFlags.InvokeMethod, Type.DefaultBinder, oSQLApp, null, CultureInfo.CurrentCulture);
21
22
//Get SQL Server Count
23
_count = Convert.ToInt32(oNames.GetType().InvokeMember("Count", BindingFlags.IgnoreCase | BindingFlags.GetProperty, Type.DefaultBinder, oNames, null, CultureInfo.CurrentCulture), CultureInfo.CurrentCulture);
24
25
//Loop through the names and add them to the list
26
for (i = 1; i < _count; i++)
27
{
28
//Add Current SQL Server Name
29
this.listBox1.Items.Add(oNames.GetType().InvokeMember("Item", BindingFlags.IgnoreCase | BindingFlags.InvokeMethod, Type.DefaultBinder, oNames, new object[1] { i }, CultureInfo.CurrentCulture));
30
}
31
32
//Set the selection to the first item in the list
33
this.listBox1.SelectedIndex = 0;
34
}
35
catch (System.InvalidCastException ex)
36
{
37
//SQLDMO object not found installed
38
MessageBox.Show(ex.Message);
39
}
40
catch (System.ArgumentNullException ex2)
41
{
42
//SQLDMO object not found installed
43
MessageBox.Show("Problem retrieving SQL Server List");
44
}
45
finally
46
{
47
this.Cursor = Cursors.Arrow;
48
}

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

其中需要用到2个Reference:
1
using System.Reflection;
2
using System.Globalization;

2
