title: Read and Modify data in web.config asp.net
body: <p>I implemented access restriction for my asp.net website using the below code in web.config</p>
  
  <pre><code>&lt;authentication mode="Windows"&gt;
    &lt;/authentication&gt;    
  &lt;authorization&gt;
    &lt;allow users="na\user1, phil\user2, so on" /&gt;
    &lt;deny users="*"/&gt;
  &lt;/authorization&gt;
  </code></pre>
  
  <p>There are few admin users for whom I should provide an interface (a web page or a modalpopup) where they can see the current users, remove users or add users to access this site. Now I want to know</p>
  
  <p>1) How to find the current users programmatically  i.e. the value of users attribute.</p>
  
  <p>I got it worked out by using below code from <a href="https://stackoverflow.com/questions/11990606/asp-net-how-do-i-reference-authorized-users-hard-coded-in-web-config-in-my-code?rq=1">asp.net How do I reference authorized users hard coded in web.config in my code</a></p>
  
  <pre><code>AuthorizationSection configSection =
    (AuthorizationSection)ConfigurationManager.GetSection("system.web/authorization");
  
      var users = new List&lt;string&gt;();
  
      var rules = configSection.Rules;
  
      foreach (AuthorizationRule rule in rules)
      {
          if (rule.Action == AuthorizationRuleAction.Allow)
          {
              foreach (string user in rule.Users)
              {
                  if (!users.Contains(user))
                  {
                      users.Add(user);
  
                  }
              }
  
          }
          //rule.Users.Add("phil\user3");
          //rule.Users.Remove("phil\\user2");
      }
  </code></pre>
  
  <p>2) How to update web.config by removing or adding users when the site is running?</p>
  
  <p>I tried adding and removing users using the commented lines from the above code but that didn't work.</p>
  
  <p>Where I am wrong in that code? As I said I need to add or remove users in the web.config on the fly so if anyone can provide me some code.
  Thanks in advance! </p>