1

在我试图进一步证明一个项目的未来时,我试图找到使用 C# 检索 Web 目录中索引/默认页面的完整路径和文件名的最佳方法,并且不知道 Web 服务器的文件名可能性列表。

'Server.MapPath("/test/")' 给我 'C:\www\test\'

...也是如此:'Server.MapPath(Page.ResolveUrl("/test/"))'

...但我需要'C:\www\test\index.html'。

有谁知道检索文件名的现有方法,当有人浏览到该目录时网络服务器将提供该文件名 - 无论是 default.aspx 还是 index.html 或其他什么?

感谢您的帮助,饲料

4

1 回答 1

5

ASP.NET 对此一无所知。您需要查询 IIS 以获取默认文档列表。

这样做的原因是 IIS 将在您的 web 文件夹中查找 IIS 默认文档列表中的第一个匹配文件,然后将脚本映射中的该文件类型(按扩展名)传递给匹配的 ISAPI 扩展名。

要获取默认文档列表,您可以执行以下操作(以默认网站为例,其中 IIS 编号 = 1):

using System;
using System.DirectoryServices;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            using (DirectoryEntry w3svc =
                 new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
            {
                string[] defaultDocs =
                    w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');

            }
        }
    }
}

然后会迭代defaultDocs数组以查看文件夹中存在哪个文件,第一个匹配项是默认文档。例如:

// Call me using: string doc = GetDefaultDocument("/");
public string GetDefaultDocument(string serverPath)
{

    using (DirectoryEntry w3svc =
         new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
    {
        string[] defaultDocs =
            w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');

        string path = Server.MapPath(serverPath);

        foreach (string docName in defaultDocs)
        {
            if(File.Exists(Path.Combine(path, docName)))
            {
                Console.WriteLine("Default Doc is: " + docName);
                return docName;
            }
        }
        // No matching default document found
        return null;
    }
}

遗憾的是,如果您处于部分信任的 ASP.NET 环境(例如共享主机)中,这将不起作用。

于 2009-06-24T15:26:52.257 回答