在C#中使用数据源名称查找SQL Server名称

时间:2017-05-22 12:52:06

标签: c# sql-server

我有一个登录窗口,我必须提供ODBC名称,数据库名称,用户ID和密码。而对于连接字符串,我需要SQL Server名称。有没有办法在ODBC名称的帮助下找到相应的SQL Server名称?我是C#编程的新手,即使有可能也不知道。

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:1)

基本上系统将DSN信息存储在HKEY_LOCAL_MACHINE \ SOFTWARE \ ODBC \ ODBC.INI

此代码基本上从注册表中读取此信息

static void Main(string[] args)
{
    string DSN = "TEST";
    using (Microsoft.Win32.RegistryKey localMachineHive = Registry.LocalMachine)
    using (RegistryKey odbcDriversKey = localMachineHive.OpenSubKey(string.Format(@"SOFTWARE\ODBC\odbc.ini\{0}", DSN)))
    {
        if (odbcDriversKey != null)
        {
            Console.Write(odbcDriversKey.GetValue("Server").ToString());
        }
    }
    Console.Read();
}

如果您需要有关DSN的更多信息,下面的代码会为您提供您可能需要的子项名称列表。

    static void Main(string[] args)
    {
        string DSN = "TEST";
        string[] subKeyNames = null;
        using (Microsoft.Win32.RegistryKey localMachineHive = Registry.LocalMachine)
        using (RegistryKey odbcDriversKey = localMachineHive.OpenSubKey(string.Format(@"SOFTWARE\ODBC\odbc.ini\{0}", DSN)))
        {
            subKeyNames = odbcDriversKey.GetValueNames();
            foreach (var subKey in subKeyNames)
            {
                Console.WriteLine(subKey.ToString());
            }

        }
        Console.Read();
    }

//Result will be 

//Driver
//Server
//LastUser
//...
//..
//.