'Winforms-Configuration Manager fails to replace the App.Config's AttachDbFilename |DataDirectory| with the application startup folder
App.Config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="myConnectionName"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;
AttachDbFilename=|DataDirectory|\AppData\MyDatabase.mdf;
Initial Catalog=MyDatabase;
Integrated Security=True;
Connection Timeout=360;
MultipleActiveResultSets=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
In another file I use
public static class ConnectionStringsHelper
{
public static string? GetConnectionStringByName(string name)
{
// Assume failure.
string? returnValue = null;
// Look for the name in the connectionStrings section.
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[name];
// If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
I would excpect the Configuration Manager to return the connection string having the |DataDirectory| part replaced by the Application StartupPath. But it Does NOT!! So I had to do it myself replacing the last
return returnValue;
with
returnValue.Replace("|DataDirectory|", Application.StartupPath);
Is this the right way to do it or I am missing something?! Thanx in advance for your help
I have also tried this:
internal static class Program
{
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
ApplicationConfiguration.Initialize();
AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(Application.ExecutablePath));
Application.Run(new Forms.MainForm());
}
}
But NO luck!! When I substitute the |DataDirectory| with the absolute Path then it works like a charm even without the
AppDomain.CurrentDomain.SetData("DataDirectory", Path.GetDirectoryName(Application.ExecutablePath));
!! Weird!!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
