It is easy to add a website to IIS statically and then open is (either on a remote server or on localhost). Just right click on the project, select “Publish”. In the dialog that opens up, just fill up all the details. Select/enter a profile. In the next pane, select a publish method. There are two interesting, but slightly different publish methods that come in the dropdown – “Web Deploy” and “Web Deploy Package”. While the “Web Deploy” will just publish the application locally, “Web Deploy Package” would create a package that can then be copied to any server wherever the application needs to be deployed, just run the executable with command prompt in administrative mode and the application is ready.
Now question is, what if we want to publish the application conditionally, meaning, on the basis of some condition, publish the application dynamically at runtime.
Microsoft provides a dynamic linking library called Microsoft.Web.Administration. To add a site, using ServerManager class, following can be written:-
ServerManager serverManager = new ServerManager(); Site mySite = serverManager.Sites.Add("<Site Name>", "<Physical Path>", <Port Number>); serverManager.CommitChanges();
Calling serverManager.commitChanges() is important. Well, our site is now published with IIS.
Similarly, in order to dynamically remove a site from the IIS, following can be done:-
ServerManager serverManager = new ServerManager(); Site mySite = serverManager.Sites["<Site Name>"]; serverManager.Sites.Remove(mySite); serverManager.CommitChanges();
Hence, we can dynamically add or delete a Site in IIS very easily. 😀