eestein
eestein

Reputation: 5114

Change AppPool of Application programmatically

I need to change the app pool of all/selected applications under a certain website. I got all websites and App Pools on my IIS, but I can't change them. Any ideas?

Here's what I've done so far... It looks strange to me, because there's only string changing, not object.

private void ChangeAppPool()
{
    Microsoft.Web.Administration.Site site = (Microsoft.Web.Administration.Site)this.websiteList.SelectedItem;
    Microsoft.Web.Administration.ApplicationPool appPool = (Microsoft.Web.Administration.ApplicationPool)this.appPoolCombo.SelectedItem;

    site.Stop();
    site.ApplicationDefaults.ApplicationPoolName = appPool.Name;

    foreach (var item in site.Applications)
    {
        item.ApplicationPoolName = appPool.Name;
    }

    site.Start();
    appPool.Recycle();
}

Upvotes: 3

Views: 7767

Answers (1)

Pilgerstorfer Franz
Pilgerstorfer Franz

Reputation: 8359

I modified your given code to use ServerManager class as your code did not work for me. (what is this.websiteList.SelectedItem? cast string to Site?)

ServerManager serverManager = new ServerManager();
Site site = serverManager.Sites[0]; // get site by Index or by siteName
ApplicationPool appPool = serverManager.ApplicationPools[1]; // get appPool by Index or by appPoolName

site.Stop();
site.ApplicationDefaults.ApplicationPoolName = appPool.Name;

foreach (var item in site.Applications)
{
    item.ApplicationPoolName = appPool.Name;
}

serverManager.CommitChanges();  // this one is crucial!!! see MSDN: 
// Updates made to configuration objects must be explicitly written to the configuration 
// system by using the CommitChanges method!!
site.Start();
appPool.Recycle();

Upvotes: 9

Related Questions