24

I use the following code to create a app pool:

var metabasePath = string.Format(@"IIS://{0}/W3SVC/AppPools", serverName);
DirectoryEntry newpool;
DirectoryEntry apppools = new DirectoryEntry(metabasePath);
newpool = apppools.Children.Add(appPoolName, "IIsApplicationPool");
newpool.CommitChanges();

How do I specify that the app pool should use .NET Framework 4.0?

Kev
  • 118,037
  • 53
  • 300
  • 385
jgauffin
  • 99,844
  • 45
  • 235
  • 372

3 Answers3

46

I see from the tags you're using IIS7. Unless you absolutely have to, don't use the IIS6 compatibility components. Your preferred approach should be to use the Microsoft.Web.Administration managed API.

To create an application pool using this and set the .NET Framework version to 4.0, do this:

using Microsoft.Web.Administration;
...

using(ServerManager serverManager = new ServerManager())
{
  ApplicationPool newPool = serverManager.ApplicationPools.Add("MyNewPool");
  newPool.ManagedRuntimeVersion = "v4.0";
  serverManager.CommitChanges();
}

You should add a reference to Microsoft.Web.Administration.dll which can be found in:

%SYSTEMROOT%\System32\InetSrv

Kev
  • 118,037
  • 53
  • 300
  • 385
  • 4
    Yes. I've switched to ServerManager. The problem was that I didn't know where the DLL for System.Web.Administration was located. The answer is `%WinDir%\System32\InetSrv\Microsoft.Web.Administration.dll` – jgauffin Jan 25 '11 at 10:38
  • 2
    `Microsoft.Web.Administration` can also be added as a NuGet Package now rather than referencing the dll directly – jgauffin Aug 18 '15 at 14:03
  • No problem. It's from an deleted answer below. (And everything is CC licensed) – jgauffin Aug 18 '15 at 19:01
  • Hi Kev - I don't think you've added the Nuget part yet. One upvote from me for this answer though :) – Chris Nevill Jan 06 '16 at 16:10
8
newpool.Properties["ManagedRuntimeVersion"].Value = "v4.0";

Will do the same thing as the Microsoft.Web.Administration.dll but using DirectoryEntry

Also

newPool.InvokeSet("ManagedPipelineMode", new object[] { 0 });

Will switch to integrated or classic pipeline mode using DirectoryEntry.

jgauffin
  • 99,844
  • 45
  • 235
  • 372
Matt
  • 89
  • 1
  • 2
2

The other answers are better in your particular scenario, but in general keep in mind that you can use the appcmd tool to do this: https://technet.microsoft.com/en-us/library/cc731784%28v=ws.10%29.aspx. Specifically:

appcmd add apppool /name: string /managedRuntimeVersion: string /managedPipelineMode: Integrated | Classic

bmm6o
  • 6,187
  • 3
  • 28
  • 55