Search code examples
iis-7virtual-directoryconfigurationsection

Create Virtual Directory and Set Permissions IIS7 - Cannot read configuration file due to insufficient permissions


I am trying to create a virtual directory and set it's permissions using IIS7 and C#. Here is a sample of my code:

using (ServerManager serverManager = new ServerManager(webSite))
{
    ConfigurationSection anonymousAuthenticationSection =
      config.GetSection(
          @"system.webServer/security/authentication/anonymousAuthentication",
          webSite);
    anonymousAuthenticationSection["enabled"] = true;

    serverManager.CommitChanges();
    return "true";
}

This throws an exception and the message is:

Cannot read configuration file due to insufficient permissions.

Can someone help?

EDIT

Running with administration privileges gives me a new error: "Enable to read configuration file" Can someone tell me which config it should be reading and how I can access it?


Solution

  • I was using the ServerManager obj incorrectly. It was not expecting the website name in the constructor. The following is the correct way to set anonymous access in IIS7.

    using (ServerManager serverManager = new ServerManager())
                    {
                        Configuration config = serverManager.GetApplicationHostConfiguration();
                        ConfigurationSection anonymouseAuthenticationSetion =                                            config.GetSection("system.webServer/security/authentication/anonymousAuthentication", webSite);
                        anonymouseAuthenticationSetion["enabled"] = true;