Introduction
This tip is about creating an Oracle DSN using C#.
Using the code
In order to create an Oracle DSN in C#, we just need to write a few lines of code. Consider the code below::
string ODBC_PATH = "SOFTWARE\\ODBC\\ODBC.INI\\";
string driverName = "Oracle in OraClient10g_home1";
string dsnName = "OracleFromCode";
string database = "MyDatabase";
string description = "This DSN was created from code!";
string server = "ORCL";
string driverPath = @"C:\Oracle\product\10.1.0\Client_1\BIN\SQORA32.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);
var dsnKey = Registry.LocalMachine.CreateSubKey(ODBC_PATH + dsnName);
if (dsnKey == null)
{
throw new Exception("ODBC Registry key not created!!");
}
dsnKey.SetValue("Database", database);
dsnKey.SetValue("Description", description);
dsnKey.SetValue("Driver", driverPath);
dsnKey.SetValue("Server", server);
dsnKey.SetValue("Database", database);
dsnKey.SetValue("userID", "DBUSER");
dsnKey.SetValue("password", "DBPWD");
In the above code, I have hardcoded some values. See below comments with code for these values:
string driverName = "Oracle in OraClient10g_home1";
string dsnName = "OracleFromCode";
string database = "MyDatabase";
string description = "This DSN was created from code!";
string server = "ORCL";
Next, you need to pass the driver (SQORA32.DLL).
At last, pass all these values to "SetValue
" (see last few lines of code). I have passed the database username and password hardcoded. You can also pass these through user inputs.