简体   繁体   中英

How to add entries to IIS virtual directory's configuration

I'm trying to add some custom properties to the configuration of a virtual directory in IIS but when I'm committing the changes I get a DirectoryNotFoundException

I've tried multiple ways of doing it, most something like this

var config = serverManager.GetWebConfiguration(serverManager.Sites[0].Name, "mycustomfolder");
var appSettings = config .GetSection("appSettings");
var collection = section.GetCollection();
var elem = conf.CreateElement("add");
elem.SetAttributeValue("key", "createdBy");
elem.SetAttributeValue("value", "me");

serverManager.CommitChanges();

The server manager object is clearly defined with

using(var serverManager = new ServerManager())
...

What I was expecting would be something like this inside the configuration:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <directoryBrowse enabled="true" />
    </system.webServer>
    <appSettings>
        <clear />
        <add key="createdBy" value="me" />
    </appSettings>
</configuration>

Instead I am getting an error

System.IO.DirectoryNotFoundException: Filename: \\?\C:\inetpub\wwwroot\local\web.config
Error: Cannot write configuration file

   at Microsoft.Web.Administration.Interop.IAppHostWritableAdminManager.CommitChanges()
   at Microsoft.Web.Administration.ConfigurationManager.CommitChanges()
   at Microsoft.Web.Administration.ServerManager.CommitChanges()

Following the path in which it is trying to save I cannot see subfolders for my virtual directories, but I can create them, even programmatically

According to your description, I guess you may used the wrong site name. I have also created a test demo on my side, it works well. I suggest you could try to use site name directly.

Details, you could refer to below codes:

    protected void Button1_Click(object sender, EventArgs e)
    {
        using (var serverManager = new ServerManager())
        {
            var config = serverManager.GetWebConfiguration("WebForm48", "mycustomfolder");
            var appSettings = config.GetSection("appSettings");
            var collection = appSettings.GetCollection();
            var elem = collection.CreateElement("add");
            elem.SetAttributeValue("key", "createdBy");
            elem.SetAttributeValue("value", "me");
            collection.Add(elem);
            serverManager.CommitChanges();
        }        
    }

My IIS console:

在此输入图像描述

Result:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM