windows 如何使用 C# 代码获取 IIS 虚拟目录和 Web 应用程序的物理路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5431713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:30:13  来源:igfitidea点击:

How to get the IIS virtual dir & web application's physical paths with C# code?

.netwindowsiis

提问by smwikipedia

I am writing a web application deployment verification tool and I need to check the physical folder structures of Web Applicatons and Virtual Folders.

我正在编写一个 Web 应用程序部署验证工具,我需要检查 Web 应用程序和虚拟文件夹的物理文件夹结构。

How can this be done in C#? OR more generally, interact with IIS through C# code?

如何在 C# 中做到这一点?或者更一般地说,通过 C# 代码与 IIS 交互?

回答by Swaff

I would strongly suggest using the Microsoft.Web.Administrationdll for superb admin features with IIS.

我强烈建议将Microsoft.Web.Administrationdll 用于 IIS 的出色管理功能。

ServerManager serverManager = new ServerManager();

// get the site (e.g. default)
Site site = serverManager.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
// get the application that you are interested in
Application myApp = site.Applications["/Dev1"];

// get the physical path of the virtual directory
Console.WriteLine(myApp.VirtualDirectories[0].PhysicalPath);

Gives:

给出:

F:\Dev\Branches\Dev1

F:\Dev\Branches\Dev1

回答by Joe

You can do this kind of thing using WMI:

您可以使用 WMI 执行此类操作:

Using WMI to configure IIS.

使用 WMI 配置 IIS

Administering IIS programatically.

以编程方式管理 IIS

And you can use WMI from C# (google for "WMI C#").

您可以使用 C# 中的 WMI(谷歌搜索“WMI C#”)。

So, yes, this is possible.

所以,是的,这是可能的。

回答by Ian

Take a look at the HttpRequestobject. You can get the current URL using HttpContext.Current.Request.Url.

看一看HttpRequest对象。您可以使用HttpContext.Current.Request.Url.

If you wanted to check that a virtual IIS folder existed you could try performing a Server.MapPathcall to the relative URL you expect to exist (again you'll find this in the HttpContextobject) and if the mapping is not successful you could then assume that a specific subfolder as specified by your relative path does not exist.

如果您想检查虚拟 IIS 文件夹是否存在,您可以尝试Server.MapPath调用您希望存在的相对 URL(您将再次在HttpContext对象中找到它),如果映射不成功,您可以假设特定的您的相对路径指定的子文件夹不存在。