创建SQL Server DSN

时间:2014-03-24 13:03:09

标签: c# dsn

我需要通过代码创建DSN以连接SQL Server。我在这个链接中尝试了这个例子,但它总是失败,因为dataSourceKey永远不会为null。有人有不同的解决方案或其他选择吗?

http://www.codeproject.com/Tips/350601/Create-SQL-DSN-in-Csharp

这是代码:

string ODBC_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";     
string driverName = "SQL Server";
string dsnName = "DSNfromCode";
string database = "MyDBName";
string description = "This DSN was created from code!";
//This is one change I made the source code had the IP of the server and I 
//am hardcoding a server name
string server = "Brimstone";
bool trustedConnection = false;

// Lookup driver path from driver name         
string driverPath = "C:\\WINDOWS\\System32\\sqlsrv32.dll"; 

var datasourcesKey = Registry.LocalMachine.CreateSubKey(ODBC_PATH + "ODBC Data Sources");         
if (datasourcesKey == null) 
{
throw new Exception("ODBC Registry key does not exist"); 
}        
    datasourcesKey.SetValue(dsnName, driverName);          
    // Create new key in odbc.ini with dsn name and add values        
    var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_PATH + dsnName);        
    if (dsnKey == null) 
{
throw new Exception("ODBC Registry key for DSN was not created"); 
}             
dsnKey.SetValue("Database", database);         
dsnKey.SetValue("Description", description);         
dsnKey.SetValue("Driver", driverPath);         
dsnKey.SetValue("LastUser", "sa");         
dsnKey.SetValue("Server", server);         
dsnKey.SetValue("Database", database);
dsnKey.SetValue("username", "sa");
dsnKey.SetValue("password", "system123#");
dsnKey.SetValue("Trusted_Connection", trustedConnection ? "Yes" : "No");

1 个答案:

答案 0 :(得分:0)

我最终只是从我的PC导出注册表项,然后在需要它的PC上的loadevent()上启动它。