数据库连接字符串中的|DataDirectory|

在.NET开发过程中,经常会在数据库连接字符串中用到|DataDirectory|,如:

    <connectionStrings>
        <add name="VideoLibrary.Properties.Settings.VideoDatabaseConnectionString"
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\VideoDatabase.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>

    <add name="MyConnection" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\MyDB.mdb;Persist Security Info=True" providerName="System.Data.OleDb" />

那么,|DataDirectory|是代表哪个路径呢?

By default this variable will be expanded as:
•For a local Application this will be the Assembly (App's .exe) folder。就是说,对于Windows应用程序(WinForm、WPF),数据库文件应该和可行性文件在同一个目录下;
•For ClickOnes running Apps it will be a special data folder created by ClickOnes。就是说,对于以ClickOnce方式运行,系统是通过AppDomain.CurrentDomain.GetData("DataDirectory")来解析的。因此,可以通过代码指定,在WPF的App构造方法中加入代码AppDomain.CurrentDomain.SetData("DataDirectory")=AppDomain.CurrentDomain.BaseDirectory;或者,AppDomain.CurrentDomain.SetData("DataDirectory", newDataPath);
•For ASP.NET App it will be App_Data folder.。对于ASP.NET,数据库文件应放在App_Data目录下。

原文地址:https://www.cnblogs.com/zhouhb/p/2808387.html