How to use a FileDsn in .Net

 

Another short one.

I saw a question on how to use FileDsn’s in a .Net application.

This may not be the most common scenario, but it can be done. I’ll show you how.

This example will assume that you have an Access database located at C:\Temp.

This Access database is called TestAcc.mdb and contains a table called TestTable.

Start the ODBC Administrator (Start -> Run -> odbcad32)

Select the File DSN tab and select “Add”.

Select the Microsoft Access Driver.

Select where you want to save the FileDsn, we can choose the C:\Temp dir for simplicity, call it MyFileDsn

Now, in the dialog where you select the Database, do so and select the file (“C:\Temp\TestAcc.mdb”)

Start your trusty Visual Studio, create a new Console application and enter the code like so:

        static void Main(string[] args)

        {

            string cstring = @"FILEDSN=C:\Temp\MyFileDsn.dsn";

            OdbcConnection con = new OdbcConnection(cstring);

            con.Open();

            OdbcDataAdapter da = new OdbcDataAdapter("SELECT * FROM TestTable", con);

            DataTable dt = new DataTable();

            da.Fill(dt);

            foreach (DataRow dr in dt.Rows)

            {

                Console.WriteLine("{0} - {1}", dr[0].ToString(), dr[1].ToString());

            }

            con.Close();

        }

This should connect to the Access database via the FileDsn and return the first two columns for each row in the TestTable.