When programatically creating a new IIS web site, how can I add it to an existing application pool?

Posted by Ian Robinson on Stack Overflow See other posts from Stack Overflow or by Ian Robinson
Published on 2010-03-12T17:10:10Z Indexed on 2010/03/15 3:29 UTC
Read the original article Hit count: 721

Filed under:
|
|

I have successfully automated the process of creating a new IIS website, however the code I've written doesn't care about application pools, it just gets added to DefaultAppPool. However I'd like to add this newly created site to an existing application pool.

Here is the code I'm using to create the new website.

var w3Svc = new DirectoryEntry(string.Format("IIS://{0}/w3svc", webserver));
var newsite = new object[] { serverComment, new object[] { serverBindings }, homeDirectory };
var websiteId = w3Svc.Invoke("CreateNewSite", newsite);
site.Invoke("Start", null);
site.CommitChanges();

<update>

Although this is not directly related to the question, here are some sample values being used above. This might help someone understand exactly what the code above is doing more easily.

  • webServer: "localhost"
  • serverComment: "testing.dev"
  • serverBindings: ":80:testing.dev"
  • homeDirectory: "c:\inetpub\wwwroot\testing\"

</update>

If I know the name of the application pool that I'd like this web site to be in, how can I find it and add this site to it?

<update 2>

I've added the following based on Mark's answer below.

        var appPool = new DirectoryEntry(string.Format("IIS://{0}/w3svc/AppPools/{1}", webServer, appPoolName));
        site.Properties["AppPoolId"].Value = appPool;

I seem to have moved passed the "RPC" error message I was initially receiving. Now this is the error message I'm receiving:

Error: System.Runtime.InteropServices.COMException (0x8000500C): Exception from HRESULT: 0x8000500C at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.PutEx(Int32 lnControlCode, String bstrName, Object vProp) at System.DirectoryServices.PropertyValueCollection.set_Value(Object value) at ProvisionIISWebsite.Query.CreateWebsite(String webServer, String serverComment, String serverBindings, String homeDirectory, String appPoolName) in C:\Users\irobinson\My Projects\ProvisionIISWebsite\Query.cs:line 104 at ProvisionIISWebsite.Query.Handle_GetData(EngineBase& caller, Boolean isSubQuery, String query, String filterField, String filterText, Debugger& debugWriter, Boolean isRendered, Int32 timeout, String customConnection) in C:\Users\irobinson\My Projects\ProvisionIISWebsite\Query.cs:line 36

</update 2>

© Stack Overflow or respective owner

Related posts about iis

Related posts about c#