Search code examples
c#iis-7sitecollection

How can you get a website application name within a website?


I want to be able to check if an application exists within an existing website but I've not found anything. At the moment I have an installer project that gets the input from the user for the name of an existing website. I use this to check the site currently exists in IIS, and if so I then want to search the existing applications to see if a particular 1 exists. Here's what I have:

private void CheckWebsiteApps()
{
    SiteCollection sites = null;

    try
    {
        //Check website exists
        sites = mgr.Sites;
        foreach (Site s in sites)
        {
            if (!string.IsNullOrEmpty(s.Name))
            {
                if (string.Compare(s.Name, "mysite", true) == 0)
                {
                    //Check if my app exists in the website
                    ApplicationCollection apps = s.Applications;
                    foreach (Microsoft.Web.Administration.Application app in apps)
                    {
                        //Want to do this
                        //if (app.Name == "MyApp")
                        //{ 
                        //    Do Something
                        //}
                    }
                }
            }
        }
    }
    catch
    {
        throw new InstallException("Can't determine if site already exists.");
    }
}

Obviously app.Name doesn't exist, so what can I do to get this?


Solution

  • You can use the Microsoft.Web.Administration and Microsoft.Web.Management API for IIS to do this. They are not in the GAC though, you have to reference them from the inetsrv folder. On my machine they are located at...

    1. C:\Windows\System32\inetsrv\Microsoft.Web.Administration.dll
    2. C:\Windows\System32\inetsrv\Microsoft.Web.Management.dll

    Here is some example code of enumerating them,

    class Program
    {
        static void Main(string[] args)
        {
            ServerManager serverManager = new ServerManager();
            foreach (var site in serverManager.Sites)
            {
                Console.WriteLine("Site -> " + site.Name);
                foreach (var application in site.Applications)
                {
                    Console.WriteLine("  Application-> " + application.Path);
                }
            }
    
    
            Console.WriteLine("Press any key...");
            Console.ReadKey(true);
        }
    }
    

    Follow Up:

    Applications do not have names, only the root Site has a name in IIS. Applications only have a path (as they are children of sites). If the Path is "/" then the Application is the root application for the site. If the path is anything other than / then it is a 2nd+ child application of the site. So you would need to use Application.Path to do what you want.