Adding a Website to IIS7 programmatically

April 16, 2008 20:32 by MartinHN

Some time ago, I blogged about Adding an Application Pool to IIS7 programmatically. The result was a new Application Pool, that uses the Integrated Pipeline in IIS7.

In this post I will show you how to add a new Website, that uses the Application Pool from the other blog post.

I've loaded the Console Application I used to add the Application Pool, and moved the logic from Main to a method called AddApplicationPool, to split it up nicely. It is actually even easier to add a website programmatically. Below is the code for doing just that:

private static void AddWebSite()
{
  ServerManager mgr = new ServerManager();

  if (!Directory.Exists(@"c:\inetpub\wwwroot\iis7test"))
  {
    Directory.CreateDirectory(@"c:\inetpub\wwwroot\iis7test");
  }

  // Add a new Site to the server, configured to use our the iis7test home directory.
  Site site = mgr.Sites.Add("MyWebSite", @"c:\inetpub\wwwroot\iis7test", 80);
  
  // Set the application pool name of the site, to use the MyAppPool application pool.
  site.ApplicationDefaults.ApplicationPoolName = "MyAppPool";

  // Clear all bindings.
  site.Bindings.Clear();

  // Make the site listen to incoming HTTP requests using host header iis7test, on port 80.
  site.Bindings.Add("*:80:iis7test", "http");
  
  // Set auto start to true.
  site.ServerAutoStart = true;

  // Commit the changes
  mgr.CommitChanges();
}

Notice how we add Bindings to the website. Bindings is the information that tells IIS7 when to serve our website. We use this string to configure bindings: *:80:iis7test. The first * tells IIS to listen on all IP addresses on your system. 80 is the port number, and iis7test is the host header value for this site.

To browse our website, we need to add iis7test to the computers hosts file (located in %WINDIR%\System32\Drivers\etc), and point it to 127.0.0.1.


kick it on DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Add to: Facebook Add to: Digg Add to: Del.icio.us Add to: Reddit Add to: Furl Add to: Yahoo Add to: Spurl Add to: Google Add to: Technorati

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen

About the author

Martin Høst Normark

Senior Frontend Developer at TraceWorks.

View Martin Høst Normark's profile on LinkedIn

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008