c# - C# 应用程序中的自定义用户配置

标签 c# .net app-config configuration-files setting

假设我有一个命令行应用程序,需要引用某种形式的用户配置文件。此外,该文件中包含的值只能由用户手动更新——没有任何方法可以更新应用程序中的配置文件,应用程序启动后也不会寻找任何输入。如果配置文件中缺少配置列表,则应使用默认值。

我知道 Visual Studio/.NET Framework 提供了用于创建此类构造的工具(即 Settings 和 App.configs),但我不确定我是否正确使用它们 - 或者我是否应该使用它们.

我创建了一个设置文件并添加了一些默认设置(例如 SomeBooleanFlag 是一个默认值为“False”的 bool 值)。当然,这一添加反射(reflect)在我的 App.config 中。然而,困境就在这里:我应该如何读取App.config?

目前,我创建了一个类来抽象配置管理器/设置内容:

class AppSettings
{
    public static bool SomeBooleanFlag
    {
        get
        {
            try
            {
                string rawValue = ConfigurationManager.AppSettings["SomeBooleanFlag"];

                bool userSetSomeBooleanFlag;
                bool userValueParsed = bool.TryParse(rawValue, out userSetSomeBooleanFlag);

                return (userValueParsed) ? userSetSomeBooleanFlag : Settings.Default.SomeBooleanFlag;
            }
            catch
            {             
                return Settings.Default.SomeBooleanFlag;
            }                
        }
    }
}

这使我能够编写:

if (AppSettings.SomeBooleanFlag) 
{ 
    /* Do Something... */ 
}

但是,这似乎不是解决我上面提到的问题的干净方法。任何帮助将不胜感激!

最佳答案

您可以重用 Visual Studio 中内置的功能来为您生成此包装器,而不是编写自己的应用程序设置包装器。请参阅How to: Add or Remove Application SettingsHow To: Read Settings at Run Time With C# 。除了指定设置的类型之外,您还可以指定范围(用户或应用程序)。

按照上述文章中的步骤,它将把设置添加到您的 App.config 文件中,下面是一个示例:

<configuration>
...
    <applicationSettings>
        <ConsoleApplication1.Properties.Settings>
            <setting name="TestKey" serializeAs="String">
                <value>TestValue</value>
            </setting>
        </ConsoleApplication1.Properties.Settings>
    </applicationSettings>
...
</configuration>

您可以按如下方式访问这些设置:

string s = Properties.Settings.Default.TestKey;

关于c# - C# 应用程序中的自定义用户配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39475736/

相关文章:

c# - Automapper - 动态类型映射

c# - 如何从 native C .dll 导出结构定义以在 C# 中使用

c# - 将跟踪监听器附加到 app.config 中的现有跟踪源

.net - 未处理的异常:System.Configuration.ConfigurationErrorsException:无法识别的元素“服务”。嵌套ConfigurationElementCollection

c# - 如何快速过滤满足日期范围条件的对象

c# - 如何初始化 IList<IList<string>>?

c# - 变量如何知道它实现的类型?

c# - ASP.NET MVC 4 - 以 HTML、JSON 或 XML 响应的正确方式

c# - Xamarin 表单中的 SwipeListView

c# - 每个配置文件的部分只能出现一次!为什么?