从ASP.NET网站获取IIS站点名称

时间:2009-10-31 16:04:20

标签: c# asp.net iis

在我的ASP.NET Web应用程序中,我想查找在IIS中创建它时给出的名称,这是服务器所独有的。我对网站的域名不感兴趣,而是对IIS中网站的实际名称感兴趣。

我需要能够可靠地为IIS6和7做到这一点。

要清楚我在谈论IIS中的给定名称,而不是域名而不是虚拟目录路径。

Value from IIS I'd like to read from C# http://img252.imageshack.us/img252/6621/capturedz.png

6 个答案:

答案 0 :(得分:57)

System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();

答案 1 :(得分:18)

正如@belugabob和@CarlosAg已经提到的,我宁愿使用System.Web.Hosting.HostingEnvironment.SiteName而不是System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()因为IApplicationHost.GetSiteName方法不是直接调用的! (msdn

所以你最好使用HostingEnvironment.SiteName属性! (msdn

我认为这应该是关于文档的正确答案;)

答案 2 :(得分:10)

以下是检索网站ID的related post

这里有一些可能适合你的代码:

using System.DirectoryServices;
using System;

public class IISAdmin
{
   public static void GetWebsiteID(string websiteName)
   {
      DirectoryEntry w3svc = new DirectoryEntry("IIS://localhost/w3svc");

     foreach(DirectoryEntry de in w3svc.Children)
     {
        if(de.SchemaClassName == "IIsWebServer" && de.Properties["ServerComment"][0].ToString() == websiteName)
        {
           Console.Write(de.Name);
        }

     }

  }
  public static void Main()
  {
     GetWebsiteID("Default Web Site");
  }

}

以下是original post的链接。

我不确定它是否可以在IIS7上运行,但是如果你为IIS7安装IIS6兼容性组件它应该可以工作。

答案 3 :(得分:9)

您正在寻找 ServerManager Microsoft.Web.Administration ),它提供对IIS 7.0配置系统的读写访问权限。

通过Microsoft.Web.Administration.SiteCollection迭代,使用站点对象获取对您网站的引用,并读取Name属性的值。

// Snippet        
using (ServerManager serverManager = new ServerManager()) { 

var sites = serverManager.Sites; 
foreach (Site site in sites) { 
         Console.WriteLine(site.Name); // This will return the WebSite name
}

您还可以使用LINQ查询ServerManager.Sites集合(请参阅下面的示例)

// Start all stopped WebSites using the power of Linq :)
var sites = (from site in serverManager.Sites 
            where site.State == ObjectState.Stopped 
            orderby site.Name 
            select site); 

        foreach (Site site in sites) { 
            site.Start(); 
        } 

注意:Microsoft.Web.Administration仅使用 IIS7

对于IIS6,您可以使用ADSI和WMI来执行此操作,但我建议您使用比ADSI更快的WMI。如果使用WMI,请查看WMI Code Creator 1.0(由Microsoft免费/开发)。它会为您生成代码。

HTH

答案 4 :(得分:0)

连接到远程服务器时,首先需要执行ServerManager.OpenRemote(“serverName”)。

基本上做这样的事情

            using (ServerManager srvMgr = ServerManager.OpenRemote("serverName"))
            {

            }

see msdn help

答案 5 :(得分:0)

您可以使用以下代码

private string WebsiteName()
{
    string websiteName = string.Empty;
    string AppPath = string.Empty;
    AppPath = Context.Request.ServerVariables["INSTANCE_META_PATH"];
    AppPath = AppPath.Replace("/LM/", "IIS://localhost/");
    DirectoryEntry root = new DirectoryEntry(AppPath);
    websiteName = (string)root.Properties["ServerComment"].Value;
    return websiteName;
}