3

I have created a Visual C# application on Visual Studio 2010 that has a database. The path is @"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Sch\AAAA\Project\Scholarships\Scholarships\Database1.mdf;Integrated Security=True;User Instance=True"

But every time I want to run the application on a different PC, I have to change the path from E:\Sch\AAAA\Project\Scholarships\Scholarships\Database1.mdf to C:\Folder1\Scholarships\Scholarships\Database1.mdf or something

Is there any way to change the path to a local path or something so that I won't have to change it every time I run the application on a different PC?

2 Answers 2

3

Use the DataDirectory substitution string

@"Data Source=.\SQLEXPRESS;" + 
"AttachDbFilename=|DataDirectory|\MyAppDataFolder\Database1.mdf;" +
"Integrated Security=True;User Instance=True"

Where is DataDirectory

|DataDirectory| (enclosed in pipe symbols) is a substitution string that indicates the path to the database. It eliminates the need to hard-code the full path which leads to several problems as the full path to the database could be serialized in different places. DataDirectory also makes it easy to share a project and also to deploy an application.

In this way the location of your database could be easily managed from inside of your application. You can change the actual directory pointed by DataDirectory using this command (before any data access code is executed)

string commonFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myAppFolder = Path.Combine(commonFolder, "MyAppDataFolder");
// This willl do nothing if the folder already exists
Directory.CreateDirectory(myAppFolder);
AppDomain.CurrentDomain.SetData("DataDirectory", myAppFolder);

This will resolve (on Win7) to C:\programdata\myappdatafolder\database1.mdf

Sign up to request clarification or add additional context in comments.

6 Comments

before \Database1.mdf do I add any other path? or just like you posted it?
Usually the correct folder is a subfolder of the CommonApplicationFolder. Added an example
I get a lot of errors on the code about commonFolder, like invalid token '('
Yes sorry, copy, paste, removed the spurious )
Οn the AppDomain.CurrentDomain i get this error Error 1 Invalid token '(' in class, struct, or interface member declaration E:\Σχολή\Τεχνολογία Λογισμικού\Εργασία\Scholarships\Scholarships\Form3.cs 17 40 Scholarships
|
2

Make the path to your db file configurable in appsettings in your app.config.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.