默认/索引页面的 C#/.NET 服务器路径

标签 c# indexing path default filenames

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

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

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

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

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

感谢您的帮助, 饲料

最佳答案

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

关于默认/索引页面的 C#/.NET 服务器路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1039062/

相关文章:

c# - SOAP 调用中的授权 header

python - pandas多索引选择: How to select subset of a dataframe?

数据库索引

sql - 优化使用索引进行聚合查询

mysql - Apache - MySQL 服务检测到错误的路径。/端口已在使用中

c# - 无法使用 C# 和 LdapConnection 对 Apache DS 进行身份验证?

c# - 将 `byte[]` 从 .NET 编码到 C 中的 `const u8*`

c# - XslCompiledTransform 与 XslTransform 以及 OOM 的比较好吗?

css - 背景图像的 src 是否与其来自 css 的路径或它所使用的文件有关?

PHP使用文件夹/图片名称中的参数制作图片数组