简体   繁体   中英

Why doesn't my System.Configuration read values in user defined section

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;
        }

Try this way.

string connectionSrt =  System.Configuration.ConfigurationManager.ConnectionStrings["BasePath"].ConnectionString;

Greetings.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM