So I'm trying to pass connection strings into my WPF application, and with every How-To I check its a simple process. Go to App.config and input the respective elements. But after doing that I try to get the values but it keeps coming up as null. No name, no key, no value. I made sure that in my references I bring in System.Configuration. I can even looking into my app.exe.config and see the element that I want to work but it still doesn't find it. Rebuild. ReRestart VS2019. Still null. Can someone please tell me what I'm doing wrong?
Here is the AppConfig
<configuration>
........
<connectionStrings>
<add name="BasePath" connectionString="CString" />
</connectionStrings>
<configuration>
And in my cs file
public static string GetConnection()
{
string result = null;
System.Configuration.Configuration config = ConfigurationManager.
OpenExeConfiguration("Filepath\app.exe");
ConnectionStringsSection section =
config.GetSection("connectionStrings")
as ConnectionStringsSection;
// Note: I have tried simply using ConfigurationManager.ConnectionStrings too
// There is a system defined connection string so its not null for that
if (section != null)
{
foreach (ConnectionStringSettings cs in section.ConnectionStrings)
{
// It doesn't even find cs with a name=BasePath
if (cs.Name == "BasePath")
{
return result = "CString";
}
}
}
return result;
}
CodePudding user response:
Try this way.
string connectionSrt = System.Configuration.ConfigurationManager.ConnectionStrings["BasePath"].ConnectionString;
Greetings.
CodePudding user response:
I forgot that I had many versions of the same application exe and I was referencing a different one in the file path than the one the system.Configuration uses. I couldn't see it in my solution explorer, but I found it by toggling with the 'ShowAllFiles' button and searching for anything with .config. After putting in the correct directory everything worked. Anyone else might find it in "app/bin/Debug/app.exe" or "app/bin/Release/app.exe"