SPServiceCollection services = SPFarm.Local.Services; foreach (SPService curService in services) { if (curService is SPWebService) { SPWebService webService = (SPWebService)curService; foreach (SPWebApplication webApp in webService.WebApplications) { foreach (SPAlternateUrl alturl in webApp.AlternateUrls) { if (alturl.Uri.ToString().Contains("http://sp")) { foreach (SPContentDatabase db in webApp.ContentDatabases) db.Unprovision(); //delete databases webApp.UnprovisionGlobally(true); //removes iis site, app pool and inetpub folder webApp.Delete(); //delete from central admin } } } } }
The function to create the WebApp and Site Collection is:
SPWebApplicationBuilder builder = new SPWebApplicationBuilder(SPFarm.Local); SPWebApplication newApplication; builder.Port = port; Uri url = new Uri("http://sp"); string host = url.Host; int port = 80; builder.HostHeader = host; builder.ApplicationPoolId = "Sharepoint - " + host + port.ToString(); builder.IdentityType = IdentityType.SpecificUser; SPFarmManagedAccountCollection manaccountcollection = new SPFarmManagedAccountCollection(SPFarm.Local); SPManagedAccount maccount = manaccountcollection.FindOrCreateAccount("DomainUser"); builder.ManagedAccount = maccount; //use the SPManagedAccount to receive the username and password automatically builder.RootDirectory = new System.IO.DirectoryInfo("C:\Inetpub\wwwroot\wss\VirtualDirectories\" + host + port.ToString()); builder.CreateNewDatabase = true; builder.DatabaseName = "WSS_Content_" + host + port.ToString(); builder.DatabaseServer = "SPDB"; builder.UseNTLMExclusively = true; newApplication = builder.Create(); // Create new web application newApplication.Provision(); SPSite mySiteCollection = newApplication.Sites.Add("/","New Site","Site Description",1033,"BLANKINTERNETCONTAINER#0","Domainme","Me","my@email.com"); mySiteCollection.Close();