Professional Programmer Notes

or just call this my soapbox

Archive for June 2011

.NET Devs: Make |DataDirectory| resolve to a path of your choosing

leave a comment »

I’m working on a desktop application that uses and embedded database. In my case, I’m using Sql Server Compact Edition 4.0 with Entity Framework 4.1. This tip could also apply to usage of Sqlite. In my app.config file, I have a connection string that tells my application to put the database in the “Data Directory” by using a syntax similar to this:

    <add name="DbConnection"
         connectionString="data source=|DataDirectory|\MyDb.sdf"
         providerName="System.Data.SqlServerCe.4.0" />

In ASP.NET, the |DataDirectory| token would expand to an App_Data folder under the root of my web application. For desktop applications, it is the bin directory. But, what if I wanted to point to a different location?

It turns out that DataDirectory is a macro. It is resolved using the AppDomain. The following line of code allows me to set the DataDirectory path prior to using the connection string:

AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\temp\data");

That would expand my connection string to: data source=C:\temp\data\MyDb.sdf


Written by curtismitchell

June 21, 2011 at 2:14 pm

Posted in Uncategorized