Get IIS site name from for an ASP.NET website
In my ASP.NET web app I'd like to look up the name it was given when it was created in IIS, which is unique to the server. I'd not interested in the domain name for the web site but the actual name given to the site in IIS.
I need to be able to do it reliably for IIS6 and 7.
To be clear I'm talking about the given name in IIS, not the domain name and not the virtual directory path.
Solution 1:
Update
As Carlos and others mentioned in the comments, it's better to use HostingEnvironment.SiteName
since GetSiteName
is not supposed to be used by users (According to the docs).
Old Solution
System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
Solution 2:
As @belugabob and @CarlosAg already mentioned I'd rather use System.Web.Hosting.HostingEnvironment.SiteName
instead of System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName()
because IApplicationHost.GetSiteName method is not intended to be called directly! (msdn)
So you're better off using HostingEnvironment.SiteName property! (msdn)
I think this should be the correct answer in respect to the documentation ;)
Solution 3:
Here is a related post in retrieving the site Id.
Here some code that might work for you:
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");
}
}
Here's the link to the original post.
I'm not sure if it will work on IIS7, but if you install the IIS6 compatibility components for IIS7 it should work.