I created a ftp site "TestFtpSite" and an application with path "/LocalUser/demor". Here is the configuration in ApplicationHost.config.
<site name="TestFtpSite" id="3">
<application path="/" applicationPool="TestFtpPool">
<virtualDirectory path="/" physicalPath="F:\empty-ftp-folder" />
</application>
<application path="/LocalUser/demor" applicationPool="TestFtpPool">
<virtualDirectory path="/" physicalPath="F:\HJ_STORAGE\demor" />
</application>
<bindings>
<binding protocol="ftp" bindingInformation="*:21:" />
</bindings>
<ftpServer>
<security>
<ssl controlChannelPolicy="SslAllow" dataChannelPolicy="SslAllow" />
<authentication>
<basicAuthentication enabled="true" />
</authentication>
</security>
<userIsolation mode="IsolateAllDirectories">
<activeDirectory />
</userIsolation>
</ftpServer>
</site>
After reading understanding-iis-url-authorization, I found that we can add location tag in ApplicationHost.config file to secure an application. But I couldn't find any code snippet or api on how to add the location tag with authorization rule to the configuration file pragmatically.
I want to achieve below pragmatically using C#.
<location path="TestFtpsite/LocalUser/Bob">
<system.ftpServer>
<security>
<authorization>
<clear />
<add accessType="Allow" users="Bob" permissions="Read, Write"/>
</authorization>
</security>
</system.ftpServer>
</location>
--------------Update----------------------
Finally, I solved it inspired by programmatically-unlocking-iis-configuration-sections-in-powershell
This is my solution, hope it will help someone.
// be sure to reference Microsoft.Web.Administration firstly
ServerManager sm = new ServerManager();
Configuration config= sm.GetApplicationHostConfiguration();
/*************************
* Unlock the section
* ***********************/
ConfigurationSection section = config.GetSection("system.ftpServer/security/authorization", "TestFtpSite/LocalUser/demor");
section.OverrideMode = OverrideMode.Allow;
sm.CommitChanges();
// Get a new instance of the configuration object
config = sm.GetApplicationHostConfiguration();
section = config.GetSection("system.ftpServer/security/authorization", "TestFtpSite/LocalUser/demor");
ConfigurationElementCollection authCollection = section.GetCollection();
ConfigurationElement clearElement = authCollection.CreateElement("clear");
authCollection.Add(clearElement);
ConfigurationElement addElement = authCollection.CreateElement("add");
addElement.SetAttributeValue("accessType", "Allow");
addElement.SetAttributeValue("users", "demor");
addElement.SetAttributeValue("permissions", "Read, Write");
authCollection.Add(addElement);
sm.CommitChanges();