从app.config临时覆盖值

时间:2012-09-27 07:41:29

标签: c# winforms configurationmanager

我的代码中有几个地方是从app.config中检索服务,如ConfigurationManager.AppSettings["ServerURL"];

现在我想让用户可以将服务URL指定为命令行参数。如果未指定参数,则必须使用app.config中的serviceurl。

在Main中,我可以执行以下操作:

if(args[0] != null)
ConfigurationManager.AppSettings["ServerURL"] = args[0]

它似乎工作,但我可以依赖AppSettings [“ServerURL”]不是从app.config重新加载?我知道ConfigurationManager.RefreshSection但它没有被使用。

1 个答案:

答案 0 :(得分:2)

不应该更改代码中的AppSettings值,而应该有另一个包装ConfigurationManager的类,并提供值替换的逻辑:

public static class Conf {
    public static string ServerURLOverride { get; set; }

    public static string ServerUrl {
        get { return ServerURLOverride ?? ConfigurationManager.AppSettings["ServerURL"]; }
    }
}

Main()

if (args.Length > 0 && args[0] != null)
    Conf.ServerURLOverride = args[0];

这也将简化单元测试。

相关问题