【问题标题】:How to read AppSettings from app.config in WinForms如何从 WinForms 中的 app.config 读取 AppSettings
【发布时间】:2020-06-25 12:35:24
【问题描述】:

我通常使用文本文件作为配置。但这次我想利用 app.config 将文件名(键)与名称(值)相关联,并使名称在组合框中可用

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
   <add key="Scenario1.doc" value="Hybrid1"/>
   <add key="Scenario2.doc" value="Hybrid2"/>
   <add key="Scenario3.doc" value="Hybrid3"/>
</appSettings>
</configuration>

这行得通吗?如何检索数据?

【问题讨论】:

    标签: c# app-config


    【解决方案1】:

    直接来自docs

    using System.Configuration;
    
    // Get the AppSettings section.        
    // This function uses the AppSettings property
    // to read the appSettings configuration 
    // section.
    public static void ReadAppSettings()
    {
      try
      {
        // Get the AppSettings section.
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
    
        // Get the AppSettings section elements.
        Console.WriteLine();
        Console.WriteLine("Using AppSettings property.");
        Console.WriteLine("Application settings:");
    
        if (appSettings.Count == 0)
        {
          Console.WriteLine("[ReadAppSettings: {0}]",
          "AppSettings is empty Use GetSection command first.");
        }
        for (int i = 0; i < appSettings.Count; i++)
        {
          Console.WriteLine("#{0} Key: {1} Value: {2}",i, appSettings.GetKey(i), appSettings[i]);
        }
      }
      catch (ConfigurationErrorsException e)
      {
        Console.WriteLine("[ReadAppSettings: {0}]", e.ToString());
      }
    }
    

    所以,如果你想访问设置Scenario1.doc,你可以这样做:

    var value = ConfigurationManager.AppSettings["Scenario1.doc"];

    编辑:

    正如 Gabriel GM 在 cmets 中所说,您必须添加对 System.Configuration 的引用。

    【讨论】:

    • 如果您没有看到ConfigurationManager,请尝试将system.configuration 添加到您的项目引用中。
    【解决方案2】:

    app.config 中的应用程序设置用于存储应用程序/环境特定设置,而不是存储绑定到 UI 的数据。

    如果您因为奇怪的业务请求而无法避免存储在配置中,我宁愿坚持一个设置

    <add key="FileDropDown" value="File1-Value|File2-Value" />
    

    并编写 C# 代码以获取此设置 ConfigurationManager.AppSettings["FileDropDown"] 并执行一些字符串拆分 ('|') 和 ('-') 以创建 kvp 集合并将其绑定到 UI。

    【讨论】:

      猜你喜欢
      • 2012-07-30
      • 2015-01-21
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-05
      • 2012-10-09
      • 1970-01-01
      相关资源
      最近更新 更多