Adding and Removing an IIS Application in .NET

Following on from an earlier post about my discovery of an API to control IIS, I had cause to investigate creating a new web application in IIS. The code, again, is remarkably simple:

            ServerManager iisManager = new ServerManager();

            Console.WriteLine("Set-up new site...");

            var sites = iisManager.Sites;

            foreach (var s in sites)
            {
                Console.WriteLine($"Site {s.Name}");

                foreach (var a in s.Applications)
                {
                    Console.WriteLine($"Application {a.Path}");
                }
            }
            Console.WriteLine(" - - - ");

            var defaultSite = sites["Default Web Site"];
            defaultSite.Applications.Add("/Test", @"c:\inetpub\betapps\test");        
            iisManager.CommitChanges();

            Console.ReadLine();

This works fine and, as you can see, is really simple. If you remove the information lines at the top, it’s three lines of code.

Remove it again

To remove the application again, try this:

            var iisManager = new ServerManager();
            var sites = iisManager.Sites;
            var defaultSite = sites["Default Web Site"];
            var testapp = defaultSite.Applications["/Test"];

            if (testapp != null)
            {
                Console.WriteLine("Remove site");
                defaultSite.Applications.Remove(testapp);
                iisManager.CommitChanges();
            }

There is an important note here; simply adding, committing changes and then removing using the same instance of ServerManager will not work. It complains that once CommitChanges is called then the object is read only:

InvalidOperation

The configuration object is read only, because it has been committed by a call to ServerManager.CommitChanges(). If write access is required, use ServerManager to get a new reference.

Also, you can’t just get around this by calling something like:

iisManager = new ServerManager();

Although this does