How can I programmatically stop or start a website in IIS (6.0 and 7.0) using MsBuild?

By adding a reference to Microsoft.Web.Administration (which can be found inX:\Windows\System32\inetsrv, or your systems equivalent) you can achieve nice managed control of the situation with IIS7, as sampled below:

namespace StackOverflow
{
    using System;
    using System.Linq;
    using Microsoft.Web.Administration;

    class Program
    {
        static void Main(string[] args)
        {
            var server = new ServerManager();
            var site = server.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
            if (site != null)
            {
                //stop the site...
                site.Stop();
                if (site.State == ObjectState.Stopped)
                {
                    //do deployment tasks...
                }
                else
                {
                    throw new InvalidOperationException("Could not stop website!");
                }
                //restart the site...
                site.Start();
            }
            else
            {
                throw new InvalidOperationException("Could not find website!");
            }
        }
    }
}

Obviously tailor this to your own requirements and through your deployment build script execute the resulting application.

Enjoy. 🙂

Leave a Comment