Adam Jenkin Adam Jenkin - 9 months ago 53
SQL Question

SQL Express connection string: mdf file location relative to application location

I am using SQL Express databases as part of a unit test project in c#. My databases is located here:


I would like to use a relative path or variable in the
rather than having my connection string defined as:


I have seen the use of
but am I correct in thinking this is only applicable to web applications?

I want to control this in the application configuration file, as in production the application uses a hosted sql database.


Thanks everyone, I used a combination of your responses.

In my app.config file my connection string is defined as follows

<add name="MyConnectionString"
    connectionString="Server=.\SQLExpress;AttachDbFilename=|DataDirectory|\MyDatabase.mdf;Database=MyDatabaseForTesting;Trusted_Connection=Yes;" />

In my unit test class I set the DataDirectory property using the following

public void TestInitialize()
    AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));

    // rest of initialize implementation ...