为什么程序会生成新的配置文件?

时间:2015-06-15 03:32:36

标签: c#

我正在改变Visual Studio中的配置文件,程序语言是C#,环境是.net framework 4.0 + windows 7.这是我的代码:

        #region change configuration file
        /// <summary>
        /// 
        /// </summary>
        /// <param name="createdTime"></param>
        [TestCase("2015-06-12 14:37:59")]
        public void ChangeConfiguration(string createdTime)
        {
            string str = System.Environment.CurrentDirectory+@"\App.config";   
            string appDomainConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            Configuration config = ConfigurationManager.OpenExeConfiguration(str);          
            AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");            
            appSettings.Settings.Remove("queryTime");
            appSettings.Settings.Add("queryTime", createdTime); 
            config.Save();
            ConfigurationManager.RefreshSection("configuration");
        }
        #endregion

程序生成一个名为App.config.config的新配置文件。这怎么可能?我只想修改原始文件中的queryTime。

ps:这是我的App.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="interval" value="5"/>
    <add key="queryTime" value="2015-06-10 14:37:59"/>
    <add key="_TimerInterval" value="5000"/>
  </appSettings>
</configuration>

1 个答案:

答案 0 :(得分:2)

这是因为OpenExeConfigurationExe名称作为输入,并自动查找配置文件名Exe.config(这是默认格式)。 -

   // Get the configuration file. The file name has 
  // this format appname.exe.config.
  System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);

您可以在此处查看示例代码 - https://msdn.microsoft.com/en-us/library/ms224437(v=vs.110).aspx

因此,在您的情况下,只需删除文件名末尾的.config -

    #region change configuration file
    /// <summary>
    /// 
    /// </summary>
    /// <param name="createdTime"></param>
    [TestCase("2015-06-12 14:37:59")]
    public void ChangeConfiguration(string createdTime)
    {
        string str = System.Environment.CurrentDirectory+@"\App";  //remove .config  
        string appDomainConfigFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
        Configuration config = ConfigurationManager.OpenExeConfiguration(str);          
        AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");            
        appSettings.Settings.Remove("queryTime");
        appSettings.Settings.Add("queryTime", createdTime); 
        config.Save();
        ConfigurationManager.RefreshSection("configuration");
    }
    #endregion