关于app.config和user.config需要一些澄清

3

我最近在Stack Overflow 和谷歌上搜索了几天关于 app.config 的信息。

我正在编写一个程序,需要使用用户输入的值生成SQL脚本。最初,我使用app.config存储一些默认值,在程序启动时加载到程序中。这很好用,直到我试图将新值存回到app.config文件中。这时,我发现app.config是只读的,我应该使用user.config

我有几个问题找不到答案:

  1. 是否建议使用settings.Setting来声明我想使用app.config的所有值?或者手动输入就足够了?

  2. 我一直在阅读关于user.config如何覆盖app.config设置的内容。但当我更新我的user.config文件时,程序仍然从原始的app.config文件中读取。

这是我的包装类代码:

public NameValueCollection ReadSettings(string sectionName)
{
        NameValueCollection scripts = null;
        try
        {
            //read in the current values from the section
            scripts = (NameValueCollection)ConfigurationManager.GetSection(sectionName);
            if (scripts == null) throw new appConfigException(String.Format("The section {0} does not exists in app.config", sectionName));
        }catch (Exception e){
            //print out the log file
            StreamWriter writer = new StreamWriter(DateTime.Now.ToString("d-MMM-yyyy") + "log.txt");
            writer.WriteLine(e.ToString());
            writer.Close();
            //kill the application process so the user cannot advance further
            System.Diagnostics.Process.GetCurrentProcess().Kill();
        }
        return scripts;
    }

ConfigurationManager是否应该自动知道从user.config开始读取?还是我需要更改代码中的此部分以反映这一点?


你是正确的,可能只需要在将其写入user.config文件后刷新要读取的部分。请参阅此帖子以了解如何重新加载配置部分:https://dev59.com/s3VC5IYBdhLWcg3wz0h9 - qJake
1个回答

1
问题1:使用Settings.settings比创建自己的配置文件yourApp.config更容易。因为使用第一种选项,您只需使用Properties.Settings.Default.MyProperty即可访问属性,而对于app.config文件,您必须处理ConfigurationManager对象,并且通常要访问属性,您需要事先知道名称,并且通常是硬编码。
问题2:是的,您是正确的,app.config与Settings.setting不同。因为您甚至可以创建一个新文件temp.config,该文件也可以用作应用程序的配置文件。
最后一个问题:我不确定,但我认为ConfigurationManager并不知道这一点,只需解析app.config文件即可。
希望有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接