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

标签 c# xml

我遇到了一些有趣的事情。我正在尝试为我们的客户制作一个快速控制台应用程序,以运行以更改他们某些程序上的某些连接字符串。这是面向客户的“快速应用”,我希望它是“白痴证明”。

应用程序所做的其中一项主要工作是在找不到默认配置文件时重新创建它。

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

        }  

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

这让我想到配置文件与它们的 exe 文件匹配的一些潜在方式?

如何让我的应用程序识别动态生成的 app.config 文件?

编辑

我添加了用于从下面的配置文件以及我的应用程序创建的当前配置文件中获取值的代码。

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

这是当前的配置文件以及真实值

<?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. 配置文件必须是程序集的名字
  2. 您需要告诉配置管理器从文件中重新加载您想要的部分,而不是内存中的部分:

    ConfigurationManager.RefreshSection("appSettings")

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

关于c# - ConfigurationManager.AppSettings 不适用于以编程方式创建的 App.config 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34325919/

相关文章:

c# - xsd.exe 在多个类文件中生成相同的枚举值

java - 如何在 Hibernate 中使用 PostgreSQL XML 字段?

xml - 柔性 3 : synchronously loading an xml file

c# - 如何在 Java 中生成伪随机字符串 "readable"?

c# - 实现主动/被动集群 : how to use Oracle for my distributed lock?

c# - 仅在第一次使用 Azure Function HttpTrigger 从主题获取消息时使用 MessageReceiver

java - JAXB:我应该如何编码复杂的嵌套数据结构?

c# - C# 中的 Debug.WriteLine() - 它有什么作用?

c# - 在 Null 引用异常中使 MoveNext() 无效

java - 从部分 XML 向 TableLayout 添加更多行