如何在.NET中读取ODBC数据源名?

事实上,所有的ODBC数据源名都存放在Windows系统的注册表中。如果你知道注册表中正确的项值,你就可以通过.NET  Framework类库提供的注册表类来读取该项值下的所有DSN列表。

所有ODBC数据源名都存放在Windows注册表下的:LocalMachine\ODBC\ODBC.INI\ODBC  Data  Sources(系统DSN)和CurrentUser\Software\ODBC\ODBC.INI\ODBC  Data  Sources(用户DSN)  键值中。

Imports  Microsoft.Win32  '引用名字空间      
 
  下面的源代码是演示读取ODBC  DSN列表内容并加入到ListBox控件中。来测试这段代码,建立一个Windows  应用程式,添加一个ListBox控件到窗体表单中,并将ReadODBCDSNs方法加到程式代码中。然后,可用一个命令按钮的单或双击事件或用窗体的导入事件来引用这个方法。

[C#]
 1private void ReadODBCSNs() 
 2        
 3            string str; 
 4            RegistryKey rootKey; 
 5            RegistryKey subKey; 
 6            string[] dsnList; 
 7            rootKey = Registry.LocalMachine; 
 8            str = "SOFTWARE\\\\ODBC\\\\ODBC.INI\\\\ODBC Data Sources"
 9            subKey = rootKey.OpenSubKey(str); 
10            dsnList = subKey.GetValueNames(); 
11            ListBox1.Items.Add("System DSNs"); 
12            ListBox1.Items.Add("================"); 
13            //string dsnName; 
14            foreach (string strdsnName in dsnList) 
15            
16                ListBox1.Items.Add(strdsnName); 
17            }
 
18            subKey.Close(); 
19            rootKey.Close(); 
20            rootKey = Registry.CurrentUser; 
21            str = "SOFTWARE\\\\ODBC\\\\ODBC.INI\\\\ODBC Data Sources"
22            subKey = rootKey.OpenSubKey(str); 
23            dsnList = subKey.GetValueNames(); 
24            ListBox1.Items.Add("================"); 
25            ListBox1.Items.Add("UserDSNs"); 
26            ListBox1.Items.Add("================"); 
27            foreach (string dsnName in dsnList) 
28            
29                ListBox1.Items.Add(dsnName); 
30            }
 
31            subKey.Close(); 
32            rootKey.Close(); 
33        }

[VB.NET]
 1Private  Sub  ReadODBCSNs()    
 2 
 3Dim  str  As  String    
 4Dim  rootKey  As  RegistryKey,  subKey  As  RegistryKey    
 5Dim  dsnList()  As  String    
 6rootKey  =  Registry.LocalMachine    
 7str  =  "SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources"    
 8subKey  =  rootKey.OpenSubKey(str)    
 9dsnList  =  subKey.GetValueNames()    
10ListBox1.Items.Add("System DSNs")    
11ListBox1.Items.Add("================")    
12Dim  dsnName  As  String    
13 
14For  Each  dsnName  In  dsnList    
15ListBox1.Items.Add(dsnName)    
16Next    
17subKey.Close()    
18 
19rootKey.Close()    
20 
21'Load  User  DSNs    
22rootKey  =  Registry.CurrentUser    
23str  =  "SOFTWARE\\ODBC\\ODBC.INI\\ODBC Data Sources"    
24subKey  =  rootKey.OpenSubKey(str)    
25dsnList  =  subKey.GetValueNames()    
26 
27ListBox1.Items.Add("================")    
28ListBox1.Items.Add("UserDSNs")    
29ListBox1.Items.Add("================")    
30 
31For  Each  dsnName  In  dsnList    
32ListBox1.Items.Add(dsnName)    
33Next    
34subKey.Close()    
35 
36rootKey.Close()    
37End  Sub    

运行效果图
posted @ 2005-06-21 09:02  冰戈  阅读(2192)  评论(8编辑  收藏  举报