Вопрос

I am needing to create a DSN through code to connect with SQL Server. I tried the example in this link, but it always fails as the dataSourceKey is never null. Does someone have a different solution or another option?

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

And this is the code:

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");
Это было полезно?

Решение

I ended up just exporting registry key from my PC and then launching it on the loadevent() on the PC that would need it.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top