ConfigurationManager.AppSettings不适用于以编程方式创建的App.config文件

时间:2022-05-29 08:05:53

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.

在测试时我注意到如果删除原始App.config文件并使用该应用程序重新创建,则所有ConfigurationManager.AppSettings行都将停止正常运行。即使我手动更改重新创建的配置文件中的值,它们也始终为每个键返回空值。

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

这让我觉得有一些基本的方式配置文件与他们的exe文件匹配?

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>

1 个解决方案

#1


1  

2 things will solve your problem.

2件事会解决你的问题。

  1. The config file needs to be the name of assembly
  2. 配置文件需要是程序集的名称

  3. 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

有关配置管理器的信息可以在MSDN中找到:https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx

#1


1  

2 things will solve your problem.

2件事会解决你的问题。

  1. The config file needs to be the name of assembly
  2. 配置文件需要是程序集的名称

  3. 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

有关配置管理器的信息可以在MSDN中找到:https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager(v=vs.110).aspx