Search code examples
c#iisftpservermanager

How do I modify an IIS FTP Authorization Rule for a specific path in C#?


In Server 2008+ I am programatically creating new folders in a virtual directory, Reports, in the FTP site. I can create a new FTP Authorization Rule for each new file path with:

using (ServerManager serverManager = new ServerManager())
{
Configuration config = serverManager.GetApplicationHostConfiguration();
ConfigurationSection authorizationSection = config.GetSection("system.ftpServer/security/authorization", "FTP/LDNClient/Reports/aClientPath");
ConfigurationElementCollection authorizationCollection = authorizationSection.GetCollection();

ConfigurationElement addElement = authorizationCollection.CreateElement("add");
addElement["accessType"] = @"Allow";
addElement["users"] = @"LDNClient";
addElement["roles"] = @"";
addElement["permissions"] = @"Read, Write";
authorizationCollection.Add(addElement);

serverManager.CommitChanges();
}

Where "FTP/LDNClient/Reports/aClientPath" is the path for the rule. But there are a large number of elements for the same user with different paths. If I open applicationHost.config I can see the different ConfigurationElements with the paths like, "aClientPath":

<location path="FTP/LDNClient/Reports/aClientPath">
    <system.ftpServer>
        <security>
            <authorization>
                <remove users="LDNClient" roles="" permissions="Write" />
                <add accessType="Allow" users="LDNClient" permissions="Read, Write" />
            </authorization>
        </security>
    </system.ftpServer>
</location>

But I can't figure out how to reference that one element so I can either (1) remove it or (2) modify the permissions. I can roll through each node with:

foreach (ConfigurationElement item in authorizationCollection)  
{
   // Do something with item here
}

But I can find the path for aClientPath in "item". Using the location node above, how would I delete it or modify its permissions?


Solution

  • I don't totally understand why it had to be this way but I took a look inside the applicationHost.config file and duplicated it. There was a remove of the "write" and an add of a "read, write". Works so I'm going to call it good enough.

                    ConfigurationElement addElement = authorizationCollection.CreateElement("remove");
                    addElement["users"] = @"LDNClient";
                    addElement["roles"] = @"";
                    addElement["permissions"] = @"Write";
                    authorizationCollection.Add(addElement);
    
                    addElement = authorizationCollection.CreateElement("add");
                    addElement["accessType"] = @"Allow";
                    addElement["users"] = @"LDNClient";
                    addElement["roles"] = @"";
                    addElement["permissions"] = @"Read, Write";
                    authorizationCollection.Add(addElement);
    
                    serverManager.CommitChanges();