在我尝试进一步面向 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/