【问题标题】:Changing values of settings files runtime更改设置文件运行时的值
【发布时间】:2016-02-11 06:09:57
【问题描述】:

我正在开发一个基于 windows 的项目,在这个项目中,我们使用了多个设置文件来设置控件的文本,例如buttons.settings、lables.settings 和.....

现在我需要在运行时将这些设置文件的内容更改为其他值,因此我们创建了具有相同“名称”列但值不同的相同设置文件,现在我真的无法更改这些设置的内容文件。

我试图通过加载并将它们保存为 xmlDocument 来更改我的拖车设置文件的内容,但不幸的是我的 app.config 不会因新值而改变。 我还使用了 ConfigurationManager.RefreshSection ...

请帮帮我 提前谢谢

【问题讨论】:

  • 你在用winforms吗?还有一个问题,您希望更改的设置在应用程序运行时生效吗?还是在重新启动应用程序后?
  • 是的,我正在使用 winform ..... 是的,我想在用户登录应用程序时在运行时更改它我会检查他的硬件锁,然后通过检查用户的版本类型来决定哪个设置内容(例如,labels2.settings)加载到我的主要设置(labels.setting)中。我能够通过 XML 加载更改设置内容并保存方法,但我的 app.config 没有得到更改
  • 我正在删除我的答案,因为我想我误解它是一个本地化问题。无论如何,您能告诉我您在 *.settings 文件中定义的设置范围是什么 - 用户吗?或应用程序?如果是用户范围,那么要使设置生效,您只需在更改 user.config 后调用Settings1.Default.Reload();。 (Settings1ApplicationSettingsBase,由 Visual Studio 在添加 Settings1.Settings 文件时自动创建),这不会更改 app.config 但更改后的值将从 user.config 文件生效
  • 感谢您的帮助,我正在使用用户范围。我想先更改设置文件,然后我希望我的 app.config 生效,但它没有改变!我坚持首先更改设置文件,因为我想用另一个设置文件的值更改设置文件中的所有值,而不仅仅是更改一些值!
  • 我现在了解您的设置。原则上,app.config 不受用户范围设置的影响绝对没问题。此行为应使每个用户都可以拥有自己的设置。如果用户没有更改设置,则使用 app.config 中的默认值。

标签: c# settings app-config multilingual


【解决方案1】:

我将从描述我的设置开始,以确保我们在同一页面上。

这是我的设置文件 - Settings1.settings,只有一个设置 Test,默认值为 DefaultValue

此时,默认值也复制到app.config中。

现在,我有一个模板,其设置将在运行时生效,其格式为 user.config。这就是它的样子——

这是来自工作实验的代码 -

private void button1_Click(object sender, EventArgs e)
    {
        MessageBox.Show(Settings1.Default.Test); // this shows "DefaultValue" in a message box

        // Now change the user.config file with our template file - 

        //1. I get the location of user config
       var fileForUser = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal).FilePath;

        //2. now I'll Place my template file, where user.config should be present 
       
        // create directory if it doesnt exist
        if(Directory.Exists(Path.GetDirectoryName(fileForUser)) == false) 
           Directory.CreateDirectory(Path.GetDirectoryName(fileForUser)) ; 
       
        // I have kept my template at E:\template.config
        File.Copy(@"E:\template.config", fileForUser, true);
       MessageBox.Show(Settings1.Default.Test); // this still shows "DefaultValue" because the user.config is not reloaded

        //3. Read the new setting 
       Settings1.Default.Reload();
       MessageBox.Show(Settings1.Default.Test); // this shows "Default Value is changed to ABC" because the user.config is now reloaded

    }

App.config 保持原样,如果我删除 user.config 或调用 Settings1.Default.Reset() 然后它的 App.config 为应用程序提供默认值

希望对您有所帮助。请让我知道它是否符合您的目的。

更新 1 支持问题作者已经尝试过的方法

这是支持你的方法的工作代码,它将把设置文件的设置带入应用程序-

后悔我的错字 - Lables2.settings,Lables.settings 而不是 Labels2.settings 和 Labels.settings

        {
            // 1. Open the settings xml file present in the same location
            string settingName = "Lables2.SETTINGS";  // Setting file name
            XmlDocument docSetting = new XmlDocument();
            docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
            XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;

            // 2. Open the config file 
            string configFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
            XmlDocument appSettingDoc = new XmlDocument();
            appSettingDoc.Load(configFile);
            XmlNodeList appConfigLabelSettings = appSettingDoc.GetElementsByTagName("userSettings")[0].
                SelectNodes("WindowsFormsApplication2.Lables")[0].ChildNodes;
            //ProjectName.Setting file

            //3. update the config file 
            for (int i = 0; i < appConfigLabelSettings.Count; i++)
            {
                var v = appConfigLabelSettings.Item(i).ChildNodes[0];
                v.InnerText = labelSettings.Item(i).InnerText;
            }

            //4. save & load the settings 
            appSettingDoc.Save(configFile);
            Lables.Default.Reload();


            MessageBox.Show(Lables.Default.Code); // test pass... shows A2
        }

我的项目设置 -

这是可执行文件夹,其中

这就是 labels2.settings 的样子

没有 xml 文档的更新 2 方法

所有设置都是相同的,这更干净。请尝试-

 {

        // 1. Open the settings xml file present in the same location
        string settingName = "Lables2.SETTINGS";  // Setting file name
        XmlDocument docSetting = new XmlDocument();
        docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
        XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;


        Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A1 GroupB1 NameC1


        //2. look for all Lables2 settings in Label settings & update
         foreach (XmlNode item in labelSettings)
         {
             var nameItem = item.Attributes["Name"];
             Lables.Default.PropertyValues[nameItem.Value].PropertyValue = item.InnerText;                
         }

         Lables.Default.Save(); // save. this will save it to user.config not app.config but the setting will come in effect in application
         Lables.Default.Reload();

         Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A2 GroupB2 NameC2

    }

【讨论】:

  • 如果我不能清楚地解释我的问题,我很抱歉!但我的问题是我没有新的配置文件,我在 .Settings 文件中有新的值,我想用新的设置文件更改设置文件的值,然后我希望 app.config 自动得到更改。
  • @Shima.Y ,很抱歉大约 10 天没有解决方案,所以我想我想清楚地了解您的设置 -
  • 你的设置是这样的吗 - 1> 你有一个默认设置的 app.config。 2> 你有setting.settings xml,保存在与应用程序运行的位置相同的位置。 3> 您想要替换此 setting.settings xml 并需要 app.config 来获取更改。这3点对吗? ---------- 您能否添加一个示例 - app.config 和 setting.settings。您还可以添加您所做的 xmlDocument 实验的代码(您在问题中提到的)吗?我想看看它,以了解您已经尝试过的内容以及无效的内容。
  • 是3个步骤都正确,我会尽快加样
  • @Shima.Y,当然。很抱歉,我刚刚注意到您已经添加了我要求的样品。我今天会处理这个。
【解决方案2】:

可能是这里提到的 xmlDocument 的问题Changing App.config at Runtime

请保持设置与我上次对 label.settings 和 label2.settings 的响应相同。

试试这个实现

{

        // 1. Open the settings xml file present in the same location
        string settingName = "Lables2.SETTINGS";  // Setting file name
        XmlDocument docSetting = new XmlDocument();
        docSetting.Load(Application.StartupPath + Path.DirectorySeparatorChar + settingName);
        XmlNodeList labelSettings = docSetting.GetElementsByTagName("Settings")[0].ChildNodes;


        Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A1 GroupB1 NameC1


        //2. look for all Lables2 settings in Label settings & update
         foreach (XmlNode item in labelSettings)
         {
             var nameItem = item.Attributes["Name"];
             Lables.Default.PropertyValues[nameItem.Value].PropertyValue = item.InnerText;                
         }

         Lables.Default.Save(); // save. this will save it to user.config not app.config but the setting will come in effect in application
         Lables.Default.Reload();

         Console.WriteLine("Code {0} Group{1} Name{2}", Lables.Default.Code, Lables.Default.Group, Lables.Default.Name); //prints Code A2 GroupB2 NameC2

    }

它对我有用,因为它没有 xmldocument,我希望它也能在年底工作。让我知道结果。

【讨论】:

  • 非常感谢卡普尔,它对我有用,我很高兴,非常感谢你
  • @Shima.Y,哇哦!!这是一个很棒的更新!相信我,我同样很高兴知道它在年底解决了问题:)
  • @Shima.Y,以防此配置设置给您未来带来任何困难(我真诚地希望,它不会,但只是以防万一),请给我写评论。
【解决方案3】:
 XmlDocument doc = new XmlDocument();
        //doc.Load(@"C:\Users\***\Documents\Visual Studio 2008\Projects\ChangingLablesRuntime\ChangingLablesRuntime\_Labels2.settings");
        //doc.Save(@"C:\Users\SHYAZDI.IDEALSYSTEM\Documents\Visual Studio 2008\Projects\ChangingLablesRuntime\ChangingLablesRuntime\_Labels.settings");

        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        var root = doc.GetElementsByTagName("userSettings")[0];
        doc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        var Config = System.Configuration.ConfigurationManager.OpenExeConfiguration(@"path of app.config");
        var root = doc.GetElementsByTagName("userSettings")[0];
        doc.GetElementsByTagName("userSettings")[0].SelectSingleNode("Zeus._Labels").InnerText = doc.GetElementsByTagName("userSettings")[0].SelectSingleNode("ChangingLablesRuntime._Labels2").InnerText;


        //var newEml = root.SelectSingleNode("ChangingLablesRuntime._Labels2");
        //var oldEml = root.SelectSingleNode("Zeus._Labels");

        //oldEml.InnerText = newEml.InnerText;

        //oldEml.ParentNode.ReplaceChild(newEml, oldEml);

        doc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile);

        Config.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection("userSettings");

这是我的代码,lables2 与 lables1 相同,但值不同,运行此代码后没有任何反应。

这是 lables1.settings 的一部分,我想用 lables2.settings 替换它: 这是一块 labels2.settings :

和app.config相关代码:

【讨论】:

  • 很抱歉,我刚刚注意到您已经添加了我要求的样本。在您今天对我的回答发表评论之后。我今天会处理这个。
  • 我添加了一个工作示例来支持您的方法。请检查,我已将其添加为我的答案的更新。让我知道它是否符合您的目的或是否有任何问题。
猜你喜欢
  • 2011-01-28
  • 1970-01-01
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
  • 2011-09-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多