SPWebApplication.Delete – Deletes Web Application – Myth Busted!!

on Monday, August 24, 2009

If someone asks you, how to delete a WebApplication from the code API, the simple answer is to use – SPWebApplication.Delete(). So logically, you would expects that when you run this command it would remove the web application from central admin (Config DB) and also remove the associated contents – Content DB and IIS WeB Application, App Pool and the home directory. (That’s the myth I am talking about)

But on close analysis found that this command only removes the Web application from the config db but rest of the associated resources remain behind (as zombies – Can’t be used). To completely delete the associated resources you need to explicitly call the commands for deleting the content DB and the IIS resources.

On research I found the sample code below works perfectly.

1: SPWebApplication wa = SPWebApplication.Lookup(new Uri(""));
3: SPContentDatabaseCollection dbColl = wa.ContentDatabases;
4: foreach (SPContentDatabase db in dbColl)
5: {
6: db.Unprovision();
7: }
9: wa.Delete();
10: wa.Unprovision();
The code SPContentDataBase.UnProvision() deletes the content dbs and the command SPWebApplication.UnProvision() deletes the IIS web site, app pool and the root folder.

The reason why this was missed in the command SPWebApplication.Delete(), I guess was to give you more granularity and power to control different actions.