在Server 2008+中,我以编程方式在FTP站点的虚拟目录Reports中创建新文件夹。我可以使用以下方法为每个新文件路径创建一个新的FTP授权规则:
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();
}
其中“ FTP / LDNClient / Reports / aClientPath”是规则的路径。但是对于具有不同路径的同一用户,存在大量元素。如果打开applicationHost.config,我可以看到带有路径的不同ConfigurationElements,例如“ 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>
但是我不知道如何引用该元素,因此我可以(1)删除它或(2)修改权限。我可以使用以下方法遍历每个节点:
foreach (ConfigurationElement item in authorizationCollection)
{
// Do something with item here
}
但是我可以在“项目”中找到aClientPath的路径。使用上面的位置节点,如何删除它或修改其权限?
这是配置管理器提供的用于修改权限的示例代码。它将基于多个属性搜索元素。
不确定它是否满足您的要求。
using System;
using System.Text;
using Microsoft.Web.Administration;
internal static class Sample {
private static void Main() {
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 = FindElement(authorizationCollection, "add", "users", @"LDNClient", "roles", @"", "permissions", @"3");
if (addElement == null) throw new InvalidOperationException("Element not found!");
addElement["permissions"] = @"Read";
serverManager.CommitChanges();
}
}
private static ConfigurationElement FindElement(ConfigurationElementCollection collection, string elementTagName, params string[] keyValues) {
foreach (ConfigurationElement element in collection) {
if (String.Equals(element.ElementTagName, elementTagName, StringComparison.OrdinalIgnoreCase)) {
bool matches = true;
for (int i = 0; i < keyValues.Length; i += 2) {
object o = element.GetAttributeValue(keyValues[i]);
string value = null;
if (o != null) {
value = o.ToString();
}
if (!String.Equals(value, keyValues[i + 1], StringComparison.OrdinalIgnoreCase)) {
matches = false;
break;
}
}
if (matches) {
return element;
}
}
}
return null;
}
}