Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationManager.AppSettings does not work with an App.config file created programmatically

Tags:

c#

xml

I ran into something interesting. I am trying to make a quick console app for our clients to run to change some connection strings on some of their programs. This being a "quick app" for clients, I want it to be "idiot proof".

One of the main things the app does is re-create a default config file should it not find it.

 if (!File.Exists("./App.config"))
        {
            Console.WriteLine("Config file is missing. Creating a new one now..");
            //file doesn't exist, let's create one.
            var doc = new XDocument(
                new XDeclaration("1.0", "UTF-16", null)
                ,new XElement("configuration"
                    , new XElement("startup"
                        , new XElement("supportedRuntime", new XAttribute("version", "v4.0")
                            , new XAttribute("sku", ".NETFramework,Version=v4.5")))
                , new XElement("appSettings"
                    , new XElement("add", new XAttribute("key", "targetDatabaseName"), new XAttribute("value", ""))
                    , new XElement("add", new XAttribute("key", "applicationServer"), new XAttribute("value", ""))
                    , new XElement("add", new XAttribute("key", "sqlServer"), new XAttribute("value", ""))
                    , new XElement("add", new XAttribute("key", "applicationServerPort"), new XAttribute("value", ""))
                    , new XElement("add", new XAttribute("key", "customSearchPath"), new XAttribute("value", "")))));


            using (var sw = new StringWriter())
            {
                using (var xw = XmlWriter.Create(sw))
                {
                    doc.Save(xw);
                    xw.Close();
                }

                doc.Save("./App.config");
                sw.Close();
                
            }

        }  

While testing I noticed that if the original App.config file is removed and re-created using the app, all of the ConfigurationManager.AppSettings lines cease to function correctly. They always return null values per each key even if I manually change the values in the re-created config file.

This leads me to think there is some underlying way config files are matched up with their exe files?

How do I get my application to recognize a dynamically generated app.config file?

Edit

I added the code I am using to grab the values from the config file below, as well as the current config file I have that has been created by my app.

 _targetDatabaseName = ConfigurationManager.AppSettings["targetDatabaseName"];
        _applicationServer = ConfigurationManager.AppSettings["applicationServer"];
        _sqlServer = ConfigurationManager.AppSettings["sqlServer"];
        _applicationServerPort = ConfigurationManager.AppSettings["applicationServerPort"];

        var emptyKeys = new List<string>();

        if (string.IsNullOrEmpty(_targetDatabaseName))
            emptyKeys.Add("targetDatabaseName");

        if(string.IsNullOrEmpty(_applicationServer))
            emptyKeys.Add("applicationServer");

        if(string.IsNullOrEmpty(_sqlServer))
            emptyKeys.Add("sqlServer");

        if(string.IsNullOrEmpty(_applicationServerPort))
            emptyKeys.Add("applicationServerPort");

        if (emptyKeys.Count > 0)
        {
            Console.WriteLine("You are missing one of the following required keys "
            + string.Join(",", emptyKeys) +". Press"
                + " a key to exit the application.");

            Console.ReadKey();
            Environment.Exit(0);
        }  

Here is the current config file as well with real values

<?xml version="1.0" encoding="utf-16"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="targetDatabaseName" value="" />
    <add key="applicationServer" value="" />
    <add key="sqlServer" value="" />
    <add key="applicationServerPort" value="" />
    <add key="customSearchPath" value="" />
  </appSettings>
</configuration>
like image 900
Adrian Avatar asked Oct 18 '22 20:10

Adrian


1 Answers

2 things will solve your problem.

  1. The config file needs to be the name of assembly
  2. You need to tell the configuration manager to reload the section you want from the file and not what is in memory:

    ConfigurationManager.RefreshSection("appSettings")

Information on the configuration manager can be found in the MSDN here: https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx

like image 86
thorkia Avatar answered Oct 30 '22 13:10

thorkia