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

Enumerate entries in TNSNames.ora using Oracle data provider class and DataSourceEnumerator

4.45/5 (5 votes)
12 Jul 2011CPOL 30.7K  
There is an easier way to get the Oracle data source than custom-code a TNSNames.ora parser.

Enumerating and writing out the entries in the default TNSNames.ora pointed to in by your system path is simple:



  • Download the Oracle data provider for .NET (ODP.NET) and install (download 32-bit or 64-bit based on your needs)
  • Make a reference to Oracle.DataAccess.

C#
using System;
using System.Data;
using System.Data.Common;
using Oracle.DataAccess.Client;
class DataSourceEnumSample
{
    static void Main()
    {
        string ProviderName = "Oracle.DataAccess.Client";
        DbProviderFactory factory = DbProviderFactories.GetFactory(ProviderName);
        if (factory.CanCreateDataSourceEnumerator)
        {
            DbDataSourceEnumerator dsenum = factory.CreateDataSourceEnumerator();
            DataTable dt = dsenum.GetDataSources();
            foreach (DataRow row in dt.Rows)
            {
                System.Diagnostics.Debug.Print(dt.Columns[0] + " : " + row[0]);
                System.Diagnostics.Debug.Print(dt.Columns[1] + " : " + row[1]);
                System.Diagnostics.Debug.Print(dt.Columns[2] + " : " + row[2]);
                System.Diagnostics.Debug.Print(dt.Columns[3] + " : " + row[3]);
                System.Diagnostics.Debug.Print(dt.Columns[4] + " : " + row[4]);
                System.Diagnostics.Debug.Print("--------------------");
            }            
        }
        else
            Console.Write("Data source enumeration is not supported by provider");
    }
}

Here is part of the output (with names changed to protect the innocent)


InstanceName : Dev.WORLD
ServerName : Dev-instance.mycompany.com
ServiceName : DEV
Protocol : TCP
Port : 1521
--------------------
InstanceName : QA
ServerName : QA-instance.mycompany.com
ServiceName : QA
Protocol : TCP
Port : 1521
--------------------
InstanceName : Prod
ServerName : prod-instance.mycompany.com
ServiceName : Prod
Protocol : TCP
Port : 1521

Please note that I did not code the above. It is in the Oracle documentation. Just search for "Oracle data provider - Developer's Guide".


If you are interested in enumerating SQL Server's, just change the provider string:


C#
string ProviderName = "System.Data.SqlClient";

Have fun coding!

License

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