C#/.NET Server Path to default/index page

时间秒杀一切 提交于 2019-12-08 07:35:49

问题


In my attempt to further future-proof a project I am trying to find the best way to retrieve the full path and filename of the index/default page in a web directory using C# and without knowing the web server's list of filename possibilities.

'Server.MapPath("/test/")' gives me 'C:\www\test\'

...so does: 'Server.MapPath(Page.ResolveUrl("/test/"))'

...but I need 'C:\www\test\index.html'.

Does anyone know of an existing method of retrieving the filename that the webserver will serve up when someone browses to that directory - be it default.aspx, or index.html, or whatever?

Thanks for any help, fodder


回答1:


ASP.NET has no knowledge of this. You would need to query IIS for the default document list.

The reason for this is that IIS will look in your web folder for the first matching file in the IIS default document list then hand off to the matching ISAPI extension for that file type (by extension) in the script mappings.

To obtain the default document list you can do the following (using the Default Website as an example where the IIS Number = 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(',');

            }
        }
    }
}

It would then be a case of iterating the defaultDocs array to see which file exists in the folder, the first match is the default document. For example:

// 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;
    }
}

Sadly this won't work if you're in a partial trust ASP.NET environment (for example shared hosting).



来源:https://stackoverflow.com/questions/1039062/c-net-server-path-to-default-index-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!