0

如何在 C# 中的应用程序的“默认文档”IIS 功能中遍历文件名?

我正在使用 Microsoft.Web.Administration.ServerManager。

谢谢

4

1 回答 1

1

您可以使用它的“松散”类型模型来完成它,基本上用于阅读它的默认网站看起来像:

using (ServerManager serverManager = new ServerManager())
{
    Configuration webConfig = serverManager.GetWebConfiguration("Default Web Site");
    ConfigurationSection section = webConfig.GetSection("system.webServer/defaultDocument");
    foreach (ConfigurationElement item in section.GetCollection("files"))
    {
        Console.WriteLine(item["value"]);
    }
}

您还可以为要经常使用的集合和条目生成强类型包装器,这使其更清晰并防止错误,这将使其看起来像:

using (ServerManager serverManager = new ServerManager())
{
    Configuration webConfig = serverManager.GetWebConfiguration("Default Web Site");
    DefaultDocumentSection section = (DefaultDocumentSection)webConfig.GetSection("system.webServer/defaultDocument", typeof(DefaultDocumentSection));
    foreach (FileElement item in section.Files)
    {
        Console.WriteLine(item.Value);
    }
}

为此,您需要以下“强类型包装器”:

public class DefaultDocumentSection : ConfigurationSection
{
    private FilesCollection _files;
    public FilesCollection Files
    {
        get
        {
            if (_files == null)
            {
                _files = (FilesCollection)base.GetCollection("files", typeof(FilesCollection));
            }

            return _files;
        }
    }

}
public class FilesCollection : ConfigurationElementCollectionBase<FileElement>
{
    protected override FileElement CreateNewElement(string elementTagName)
    {
        return new FileElement();
    }
}

public class FileElement : ConfigurationElement
{
    public string Value { get { return (string)base["value"]; } }
}
于 2013-04-09T00:01:10.573 回答