Is it possible to specify a relative path reference in connectionstring, attachDbFileName property in a web.config?
For example, In my database is located in the App
Web.config
<appSettings>
<add key="FilePath" value="App_Data\SavedFiles\"/>
</appSettings>
Path.cs
string filePath = AppDomain.CurrentDomain.BaseDirectory + (ConfigurationManager.AppSettings["FilePath"]);
Works for me..!!
I had the same problem with the following scenario: I wanted to use the same database as the application from my integration tests.
I went with the following workaround:
In the App.config of my test-project I have:
<appSettings>
<add key="DataDirectory" value="..\..\..\BookShop\App_Data\"/>
</appSettings>
In the test-setup I execute the following code:
var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];
var absoluteDataDirectory = Path.GetFullPath(dataDirectory);
AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory);
Add the following attributes to the test method:
[DeploymentItem("..\\TestSolutionDir\\TestProjedtDir\\TestDataFolder\\TestAutomationSpreadsheet.xlsx")]
[DataSource("System.Data.Odbc", "Dsn=Excel Files;dbq=|DataDirectory|\\TestAutomationSpreadsheet.xlsx", "SpreadsheetTabName$", DataAccessMethod.Sequential)]
The |DataDirctory|
variable is defined by the system when it runs the test. The DeploymentItem copies the spreadsheet there. You point to the spreadsheet and to the tab within the spreadsheet that the data is coming from. Right-click on the tab to rename it to something easy to remember.
It depends on where your '|DataDirectory|' is located. If the resolved value of '|DataDirectory|' is in folder A (where the web.config is), then no - you can't specify a relative path that is not a subfolder of the resolved value of '|DataDirectory|'.
What you can do is set the value of '|DataDirectory|' to be wherever you would like, by calling the AppDomain.SetData method.
From the MSDN online documentation:
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.
Hope this helps.
In IIS you could also create a virtual directory that points at wherever the the real database is kept. Then your connection string just references the virtual directory.