locked
Configuration.SaveAs(Path) throws ConfigurationErrorsException when called the second time. RRS feed

  • Question

  • User1587670440 posted

    I am currently working on creating new config files with custom settings. I have no problem calling the config.saveAs(path) the first time, but the same function will throw this exception when being called the second time:

    "System.Configuration.ConfigurationErrorsException: 'The configuration file has been changed by another program."

    I dont understand why this exception is thrown because "ConfigurationManager.RefreshSection(sectionName);" is called on the next line.Here is some code:

                string sectionName = "Recipe_Config";
                string path = @"Recipe.config";
                string newPath1 = @"Recipe1.config";
                string newPath2 = @"Recipe2.config";
    
                ConfigurationFileMap map = new ConfigurationFileMap(path);
                Configuration config = ConfigurationManager.OpenMappedMachineConfiguration(map);
                config.SaveAs(newPath1);
                ConfigurationManager.RefreshSection(sectionName);
                config.SaveAs(newPath2); //exception here
                ConfigurationManager.RefreshSection(sectionName);
                Console.WriteLine("..save as done");
                Console.ReadLine();

    Thanks

    Lew

    Monday, March 8, 2021 7:41 AM

Answers

  • User-939850651 posted

    Hi Lew YE,

    According to the code you provided, I tested them, and I think you need to recreate the configuration object after the SaveAs() method.

    Something like this:

    string sectionName = "Recipe_Config";
                string path = @"Recipe.config";
                string newPath1 = @"Recipe1.config";
                string newPath2 = @"Recipe2.config";
    
                ConfigurationFileMap map = new ConfigurationFileMap(path);
                Configuration config = ConfigurationManager.OpenMappedMachineConfiguration(map);
                config.SaveAs(newPath1);
                ConfigurationManager.RefreshSection(sectionName);
    
                map = new ConfigurationFileMap(path);
                config = ConfigurationManager.OpenMappedMachineConfiguration(map);
                config.SaveAs(newPath2);
                ConfigurationManager.RefreshSection(sectionName);
                Console.WriteLine("..save as done");
                Console.ReadLine();

    Hope this can help.

    Best regards,

    Xudong Peng

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, March 9, 2021 7:36 AM