Get IIS site name from for an ASP.NET website

后端 未结 6 1246
长发绾君心
长发绾君心 2021-02-02 05:59

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 si

6条回答
  •  被撕碎了的回忆
    2021-02-02 06:18

    You are looking for ServerManager (Microsoft.Web.Administration) which provides read and write access to the IIS 7.0 configuration system.

    Iterate through Microsoft.Web.Administration.SiteCollection, get a reference to your website using the Site Object and read the value of the Name property.

    // 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
    }
    

    You can also use LINQ to query the ServerManager.Sites collection (see example below)

    // 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(); 
            } 
    

    Note : Microsoft.Web.Administration works only with IIS7.

    For IIS6 you can use both ADSI and WMI to do this, but I suggest you to go for WMI which is faster than ADSI. If using WMI, have a look at WMI Code Creator 1.0 (Free / Developed by Microsoft). It will generate the code for you.

    HTH

提交回复
热议问题