Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Create an Oracle DSN in C#

5.00/5 (3 votes)
29 Mar 2012CPOL 21.3K  
Create an Oracle Data Source Name programmatically.

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::

C#
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"; //TSN Name

string driverPath = @"C:\Oracle\product\10.1.0\Client_1\BIN\SQORA32.DLL";

// value to odbc data source         
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);

//It will Create new key in odbc.ini         
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:

C#
string driverName = "Oracle in OraClient10g_home1"; //Name of your Oracle Driver
string dsnName = "OracleFromCode";//Name of your DSN
string database = "MyDatabase";//Name of the Database or Tablespace
string description = "This DSN was created from code!";//Description (Optional)
string server = "ORCL"; //TSN Name of the oracle

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)