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

2019-06-01 01:47发布

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条回答
Ridiculous、
2楼-- · 2019-06-01 02:04

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).

查看更多
登录 后发表回答