Search code examples
c#databasepathlocal

Visual C# Creating a database path so that it runs on different PCs


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?


Solution

  • 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