Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

./Databases/MyUnitTestDB.mdf 

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

AttachDbFilename=C:\blah\blah\blah\yea\yea\yea\MyApplication\Databases\MyUnitTestDB.mdf  

I have seen the use of |DataDirectory| 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.

like image 725
Adam Jenkin Avatar asked Aug 17 '10 08:08

Adam Jenkin


People also ask

Where is SQL MDF file location?

Default Location of MDF File in SQL Server Files that are common and used by all instances on a single system are installed inside the folder :\Program Files\Microsoft SQL Server\nnn\.

Where is SQL Express connection string?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.

Where is the information related to database connection string is stored?

Applications use connection strings to identify the server instance and database to connect to and to determine what driver, login, etc. to use to connect to the SQL Server instance. Typically, the connection string will be stored in a configuration file somewhere within the application or web server.

How are database connection strings stored?

Connection strings can be stored as key/value pairs in the connectionStrings section of the configuration element of an application configuration file. Child elements include add, clear, and remove.


1 Answers

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

[TestInitialize] public void TestInitialize() {     AppDomain.CurrentDomain.SetData("DataDirectory", System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Databases"));      // rest of initialize implementation ... } 
like image 55
Adam Jenkin Avatar answered Sep 19 '22 20:09

Adam Jenkin