Click here to Skip to main content
15,891,704 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hi am trying to modify the web.config file on run time. My application uses windows authentication. The code which I have written is working fine on my local system. But when i host the application in the IIS on the server, application is throwing an error, when I try to modify web.config file on run time.
below is the code used to modify the the web.config file.
C#
protected void btnAdd_Click(object sender, EventArgs e)
   {
       AuthorizationSection section;
       System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);

       section = (AuthorizationSection)config.GetSection("system.web/authorization");

       AuthorizationRule arule = new AuthorizationRule(AuthorizationRuleAction.Allow);

       string[] strAllowedUsers = GetUsers();


       section.Rules.Clear();

       foreach (string element in strAllowedUsers)
       {
           arule.Users.Add(element);
       }
       arule.Users.Add(txtAddUser.Text.ToString());
       section.Rules.Add(arule);



       config.Save();

   }

private string[] GetUsers()
   {
       string[] strUser = null;
       try
       {
           AuthorizationSection section;
           System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
           section = (AuthorizationSection)config.GetSection("system.web/authorization");

           var rules = section.Rules;
           var allowedUsers = rules
             .OfType<authorizationrule>()
             .Where(r => r.Action == AuthorizationRuleAction.Allow)
             .Select(r => r.Users).First();
           if (allowedUsers.ToString() != null)
               strUser = allowedUsers.ToString().Split(',');
       }
       catch { }
       return strUser;
   }

It throws an error -->
SQL
Unable to save config to file 'c:\inetpub\wwwroot\myapplication\web.config


Note: I am hosting the application on IIS 5.1
Posted
Updated 27-Jul-13 2:33am
v4
Comments
Thanks7872 27-Jul-13 8:32am    
Why such a weird logic? Why you want to modify web config at runtime?
pradiprenushe 27-Jul-13 12:43pm    
This is permission issue to the web config file?

1 solution

you should not be modifying web.config file at runtime. If you have to do something like that, add another xml file to your project and modify that and read values from that file. It will work fine.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900