WebConfig.ConnectionString中的相对路径参考

时间:2020-03-06 14:38:24  来源:igfitidea点击:

是否可以在web.config中的connectionstring,attachDbFileName属性中指定相对路径引用?

例如,在我的数据库位于App_data文件夹中,我可以轻松地将AttachDBFilename指定为| DataDirectory | \ mydb.mdf和| Datadirectory |。将自动解析为正确的路径。

现在,假设web.config文件位于A文件夹中,但是数据库位于B \ App_data文件夹中,其中A和B文件夹位于同一文件夹中。无论如何,有没有使用相对路径引用来解析为正确路径的方法?

解决方案

这取决于" | DataDirectory |"位于。如果解析的值是" | DataDirectory |"在文件夹A(web.config所在的文件夹)中,那么,我们不能指定一个相对路径,该相对路径不是'| DataDirectory |'解析值的子文件夹。

我们可以做的是设置'| DataDirectory |'的值。通过调用AppDomain.SetData方法将其设置为我们想要的任何位置。

从MSDN联机文档中:

When DataDirectory is used, the resulting file path cannot be higher in the directory structure than the directory pointed to by the substitution string. For example, if the fully expanded DataDirectory is C:\AppDirectory\app_data, then the sample connection string shown above works because it is below c:\AppDirectory. However, attempting to specify DataDirectory as |DataDirectory|..\data will result in an error because \data is not a subdirectory of \AppDirectory.

希望这可以帮助。

在IIS中,我们还可以创建一个虚拟目录,该目录指向实际数据库的保存位置。然后,连接字符串仅引用虚拟目录。

在以下情况下,我遇到了同样的问题:我想使用集成测试中与应用程序相同的数据库。

我采用以下解决方法:

在我的测试项目的App.config中,我有:

<appSettings>
  <add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/>
</appSettings>

在测试设置中,我执行以下代码:

var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];  
   var absoluteDataDirectory = Path.GetFullPath(dataDirectory);  
   AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory);