动态编辑app.config值

时间:2013-12-17 11:18:00

标签: c# configuration app-config

我想从我的项目中动态更改一个值是我的app.config。

这是我的app.config:

<?xml version="1.0"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
 <system.web>
   <membership defaultProvider="SqlProvider">
   <providers>
    <clear />
    <add name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MySqlConnection"
         enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false"
         applicationName="app1" requiresUniqueEmail="false"
         passwordFormat="Hashed" maxInvalidPasswordAttempts="6545"
         minRequiredPasswordLength="4" minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10" passwordStrengthRegularExpression=""/>
   </providers>
   </membership>
 </system.web>
</configuration>

我想在'sqlProvider'中更改'applicationName'键的值。

我在网上找到的所有人都在使用:

 ConfigurationManager.AppSettings["key"]

但这对我不起作用。

1 个答案:

答案 0 :(得分:0)

ConfigurationManager.AppSettings [“key”]通常使用“AppSettings”部分下定义的设置。你可以试试下面的代码 -

public class MembershipSetting
{
    /// <summary>
    /// Gets or sets the name of the setting.
    /// </summary>
    public string SettingName { get; set; }

    /// <summary>
    /// Gets or sets the setting value.
    /// </summary>
    public string SettingValue { get; set; }
}

  private List<MembershipSetting> GetMembershipSetting()
    {
        List<MembershipSetting> settings = new List<MembershipSetting>
                            {
                                new MembershipSetting {SettingName = "Dafult Membership Provider", SettingValue = Membership.Provider.ToString() },
                                new MembershipSetting {SettingName = "Minimum Required Password Length", SettingValue = Membership.MinRequiredPasswordLength.ToString(CultureInfo.InvariantCulture) },
                                new MembershipSetting {SettingName = "Minimum Required Non Alphanumeric Characters",SettingValue = Membership.MinRequiredNonAlphanumericCharacters.ToString(CultureInfo.InvariantCulture)},
                                new MembershipSetting {SettingName = "Password reset enabled", SettingValue = Membership.EnablePasswordReset.ToString()},
                                new MembershipSetting {SettingName = "Maximum Invalid Password Attempts",SettingValue = Membership.MaxInvalidPasswordAttempts.ToString(CultureInfo.InvariantCulture) },
                                new MembershipSetting {SettingName = "Attempt windows",SettingValue = Membership.PasswordAttemptWindow.ToString(CultureInfo.InvariantCulture)},
                                new MembershipSetting {SettingName = "applicationName",SettingValue = Membership.ApplicationName.ToString(CultureInfo.InvariantCulture)}
                            };

        return settings;
    }

本文最初发布于here