Zayko in the Net

Personal blog of Vitaly Zayko


Do you know that you can use system variable "|DataDirectory|" to connect to your local SQL database (C#)?

In my last post I shared a function that returns path to current Assembly that could be used in a database connection string. But do you know that you have a shorter way to get this path? Use "|DataDirectory|" in your connection string instead:

 private string GetConnectionString()
     return "Microsoft.SQLSERVER.MOBILE.OLEDB.3.0;Data Source=|DataDirectory|\\Data.sdf";

By default this variable will be expanded as:
  • For a local Application this will be the Assembly (App's .exe) folder;

  • For ClickOnes running Apps it will be a special data folder created by ClickOnes;

  • For ASP.NET App it will be App_Data folder.

Because the |DataDirectory| is a property of App domain, you can change its value by doiung

 AppDomain.CurrentDomain.SetData("DataDirectory", newDataPath);

Add comment