【问题标题】:C#/.NET Server Path to default/index page默认/索引页面的 C#/.NET 服务器路径
【发布时间】:2010-11-05 13:27:04
【问题描述】:

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

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

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

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

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

感谢您的帮助, 饲料

【问题讨论】:

    标签: c# indexing path default filenames


    【解决方案1】:

    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 环境(例如共享主机)中,这将不起作用。

    【讨论】:

    • 没问题。我日复一日地生活和呼吸这些东西。 :)
    • 小心,因为这一行: new DirectoryEntry("IIS://Localhost/W3SVC/1/root") 因为这仅在应用程序安装在默认网站( 1 是指归属于默认网站的数字)。如果应用程序安装在另一个网站上,则该数字会有所不同。
    • @joerage - 显然,但它是如何做到这一点的一个例子......也就是说我已经在答案中更清楚地说明了这一点。
    猜你喜欢
    • 1970-01-01
    • 2014-07-20
    • 2022-01-04
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 2012-05-24
    • 1970-01-01
    • 2015-04-14
    相关资源
    最近更新 更多