【问题标题】:Write values in app.config file在 app.config 文件中写入值
【发布时间】:2011-01-21 12:06:11
【问题描述】:

谁能帮助我如何使用 c# 在 app.config 文件中设置/存储值,这可能吗?

【问题讨论】:

  • 你用谷歌搜索过这个吗?
  • 您能说得更具体一点吗?您不想存储什么样的值,何时存储?通常不建议在 App 配置中存储应用程序范围的值(如字符串或整数)。
  • 问一个在专业人士看来很愚蠢的问题是可以的,每个人都从头开始。但是,即使不进行简单的谷歌搜索也很糟糕。
  • 我尝试过,也搜索过,尝试了几种方法,但没有运气。这就是为什么我这么问..
  • 由于您对这一切似乎很陌生,我想补充一点,这些设置需要在您的 .exe.config 文件中。如果您尝试从 dll 获取或设置(即类库项目或除我见过的 mstest 项目之外的任何其他项目),它将无法正常工作。它想要你的应用程序 exe 文件!否则你将需要hackery。为了清楚起见,我指的是为此使用 ConfigurationManager。

标签: c#


【解决方案1】:

试试下面的代码:

    Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
    config.AppSettings.Settings.Add("YourKey", "YourValue");
    config.Save(ConfigurationSaveMode.Minimal);

它对我有用:-)

【讨论】:

  • 谢谢,命名空间是 System.Configuration。所以 System.Configuration.Configuration config = ....
  • “访问路径被拒绝”当我尝试安装它时。但是当我在visual studio中尝试它时它工作正常。你能帮帮我吗?
【解决方案2】:

在 Framework 4.5 上,ConfigurationManager 的 AppSettings.Settings["key"] 部分是只读的,因此我必须先删除密钥,然后使用以下命令再次添加:

Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);

config.AppSettings.Settings.Remove("MySetting");
config.AppSettings.Settings.Add("MySetting", "some value");

config.Save(ConfigurationSaveMode.Modified);

不用担心,如果您尝试删除不存在的密钥,您不会收到异常。

post 给出了一些很好的建议

【讨论】:

    【解决方案3】:
    private static string GetSetting(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }
    
    private static void SetSetting(string key, string value)
    {
        Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        configuration.AppSettings.Settings[key].Value = value;
        configuration.Save(ConfigurationSaveMode.Full, true);
        ConfigurationManager.RefreshSection("appSettings");
    }
    

    【讨论】:

    • 我必须添加 configuration.AppSettings.Settings.Add(value);在配置之前。AppSettings.Settings[key].Value = value;当 .config 文件为空时让它工作。
    • 使用Settings.Add()时,如果条目不存在,则添加,如果已经存在,则将值添加到现有值中,以逗号分隔。例如。调用Settings.Add("myKey", "test") 4 次后,您的条目将变为:<key = "myKey" value = "test, test, test" />
    • ConfigurationManager.RefreshSection("appSettings");对我来说是关键,如果你不这样做,读取新写入的值将不起作用。
    • 我建议使用ConfigurationManager.RefreshSection(configuration.AppSettings.SectionInformation.Name) 而不是硬编码字符串。
    【解决方案4】:

    如果您使用 App.Config 将值存储在 <add Key="" Value="" /> 或 CustomSections 部分,请使用 ConfigurationManager 类,否则使用 XMLDocument 类。

    例如:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <appSettings>
        <add key="server" value="192.168.0.1\xxx"/>
        <add key="database" value="DataXXX"/>
        <add key="username" value="userX"/>
        <add key="password" value="passX"/>
      </appSettings>
    </configuration>
    

    您可以使用CodeProject上发布的代码

    【讨论】:

      【解决方案5】:

      正如其他人提到的,您可以使用ConfigurationManager.AppSettings.Settings 执行此操作。但: 如果密钥不存在,则使用 Settings[key] = value 将不起作用。
      使用Settings.Add(key, value),如果键已经存在,它将把新值加入到它的值中,用逗号分隔,比如 &lt;add key="myKey" value="value1, value2, value3" /&gt;

      为避免这些意外结果,您必须处理两种情况

      • 是否存在具有给定键的条目?然后更新它的值
      • 如果具有给定键的条目不存在?然后创建新条目(键,值)

      代码

      public static void Set(string key, string value)
      {
          var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
      
          var entry = config.AppSettings.Settings[key];
          if (entry == null)
              config.AppSettings.Settings.Add(key, value);
          else
              config.AppSettings.Settings[key].Value = value;
      
          config.Save(ConfigurationSaveMode.Modified);
      }
      

      有关检查entry == null的更多信息,请检查this post
      希望这会对某人有所帮助。

      【讨论】:

        【解决方案6】:

        对于 .NET 4.0 控制台应用程序,这些都不适合我。因此,我使用了以下内容并且成功了:

        private static void UpdateSetting(string key, string value)
        {
            Configuration configuration = ConfigurationManager.
                OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
            configuration.AppSettings.Settings[key].Value = value;
            configuration.Save();
        
            ConfigurationManager.RefreshSection("appSettings");
        }
        

        【讨论】:

          【解决方案7】:
          string filePath = System.IO.Path.GetFullPath("settings.app.config");
          
          var map = new ExeConfigurationFileMap { ExeConfigFilename = filePath };
          try
          {
              // Open App.Config of executable
              Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
          
              // Add an Application Setting if not exist
          
                  config.AppSettings.Settings.Add("key1", "value1");
                  config.AppSettings.Settings.Add("key2", "value2");
          
              // Save the changes in App.config file.
              config.Save(ConfigurationSaveMode.Modified);
          
              // Force a reload of a changed section.
              ConfigurationManager.RefreshSection("appSettings");
          }
          catch (ConfigurationErrorsException ex)
          {
              if (ex.BareMessage == "Root element is missing.")
              {
                  File.Delete(filePath);
                  return;
              }
              MessageBox.Show(ex.Message);
          }
          

          【讨论】:

          • 此响应的独特之处在于它显示了如何打开任意命名的配置文件,而不仅仅是 *.exe.config 文件;与其他回复不同。
          【解决方案8】:

          是的,您可以 - 请参阅 ConfigurationManager

          ConfigurationManager 类 包括使您能够 执行以下任务:

          • 整体读写配置文件。

          学习使用docs,它们应该是您解决此类问题的第一站。

          【讨论】:

            【解决方案9】:

            尝试以下方法:

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);            
            config.AppSettings.Settings[key].Value = value;
            config.Save();
            ConfigurationManager.RefreshSection("appSettings");
            

            【讨论】:

              【解决方案10】:
              //if you want change
              Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
              config.AppSettings.Settings[key].Value = value;
              
              //if you want add
              Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
              config.AppSettings.Settings.Add("key", value);
              

              【讨论】:

                【解决方案11】:

                我为此苦苦挣扎了一段时间,终于自己解决了。我当时没有找到任何帮助,但想分享我的方法。我已经这样做了好几次,并使用了与上面不同的方法。不确定它有多强大,但它对我有用。

                假设您有一个名为“txtName”的文本框和一个名为“btnSave”的按钮,并且您想保存名称,以便下次运行程序时,您键入的名称会出现在该文本框中。

                1. 转到项目>属性>设置并创建设置-
                • name = "姓名"
                • type = "字符串"
                • 范围=“用户”
                • 值可以留空。

                保存您的设置文件。

                1. 转到存在文本框和按钮的表单。双击您的按钮并输入此代码;
                    //This tells your program to save the value you have to the properties file (app.config);
                    //"Name" here is the name you used in your settings file above.
                    Properties.Settings.Default.Name = txtName.txt;
                    //This tells your program to make these settings permanent, otherwise they are only
                    //saved for the current session
                    Properties.Settings.Default.Save();
                
                1. 转到您的 form_load 函数并将其添加到那里;
                    //This tells your program to load the setting you saved above to the textbox
                    txtName.txt = Properties.Settings.Default.Name;
                
                1. 调试您的应用程序,您应该会看到您输入的名称。
                2. 检查您的应用程序调试目录,您应该会看到一个以您的程序命名的 .config 文件。使用文本编辑器打开它,您将看到您的设置。

                注意事项-

                • “名称”是指您创建的设置的实际名称。
                • 您的程序将负责创建实际的 XML 文件,您不必担心。

                【讨论】:

                • 没有项目>属性>设置
                猜你喜欢
                • 1970-01-01
                • 2010-12-14
                • 1970-01-01
                • 2012-06-23
                • 2010-11-16
                • 2017-07-12
                • 1970-01-01
                • 2012-08-30
                • 1970-01-01
                相关资源
                最近更新 更多