Click here to Skip to main content
Click here to Skip to main content

Stop/Start IIS Website in .NET (C#)

, 31 Oct 2007
Rate this:
Please Sign up or sign in to vote.
I have seen a number of requests for Website control in C#, but no examples. So here it is at last!
Screenshot - websitecontrol.gif

Introduction

In my search for a program to stop and start Web sites programmatically, I saw examples of handling IIS in VB Script, but not in .NET. I also found examples of WMI in C# and VB.NET, but not for working with IIS. I decided to put the two ideas together and came up with this example. I did borrow the WMI ideas in this code from another article I read. I wish I could remember which one, so I could reference it.

This is the second incarnation of this article. Since the first, I have cleaned up the code and added some comments. I have also enhanced the code to support monitoring and controlling remote systems (depending on access rights).

Using the Code

I will elaborate on two sections of the code. For complete details, please refer to the source code provided.

Below is an excerpt from the method which returns a list of the Web sites which exist on the selected server. The getDirectoryEntry method uses an alternate user id and password if provided. Using ActiveDirectory, we enumerate the children of IIS, collecting the Web site names (assumed to be stored in the "ServerComment" property) for display in the Web sites combo box.

List<string> siteNames = new List<string>();

DirectoryEntry root = getDirectoryEntry("IIS://" + txtServer.Text + "/W3SVC");

foreach (DirectoryEntry e in root.Children)
{
    if (e.SchemaClassName == "IIsWebServer")
    {
        siteNames.Add(e.Properties["ServerComment"].Value.ToString());
    }
}  

This next section is the part I have, till now, been unable to find in code for .NET. First, the ConnectionOptions object is created and set up with the optional user id and password if provided.

ConnectionOptions connectionOptions = new ConnectionOptions();

if (txtUserID.Text.Length > 0)
{
    connectionOptions.Username = txtUserID.Text;
    connectionOptions.Password = txtPassword.Text;
}
else
{
    connectionOptions.Impersonation = ImpersonationLevel.Impersonate;
} 

Next, we need a ManagementScope object which is used to work with the local or remote server's IIS objects. Note use of microsoftiisv2 below. The ConnectionObject is used here as well to provide authentication.

ManagementScope managementScope =
    new ManagementScope(@"\\" + txtServer.Text + @"\root\microsoftiisv2", 
        connectionOptions);

managementScope.Connect();

The SelectQuery returns a collection of Web sites, but in this case just one, since it's by Site ID. It is not included in this example, but in the source code you will see that we find the Site ID for the currently selected Web site before calling this method. Using the ManagementObject returned from the ManagementObjectSearcher, we invoke the appropriate method (Start or Stop). The InvokeMethod method also requires an object array of parameters. Stop and Start do not require any parameters, so we pass an empty object array.

SelectQuery selectQuery =
    new SelectQuery("Select * From IIsWebServer Where Name = 'W3SVC/" + site + "'");
using (ManagementObjectSearcher managementObjectSearcher = 
        new ManagementObjectSearcher(managementScope, selectQuery))
{
    foreach (ManagementObject objMgmt in managementObjectSearcher.Get())
        objMgmt.InvokeMethod(state.ToString(), new object[0]);
} 

In my use of this program, it works fine where I use Windows Authentication. If I enter a valid user ID and password, it also works. I don't have an environment where Windows Authentication is not enabled, so your use of the user ID and password may vary. If there is a problem with that part of this code and someone out there knows how to fix it, I'd love to hear about it so I can revise this article to reflect that.

History

  • Second version: 11/4/2007
    The second edition is more complete and hopefully easier to understand.
  • First version: 10/31/2007
    This is my first article and I didn't have much time to spend writing it. Hopefully future articles will be more complete.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tom Faust
Web Developer
United States United States
I have been writing code since the late 70's. After learning COBOL and RPG II in school, I proceeded never to use them again, moving quickly on to BASIC, C, Assembler, Perl and others. Eventually to Java, C# and VB.Net. C# is my favorite of the bunch although Java (my first object oriented language, having skipped over C++) holds a close second.
 
I live in the state of Washington and love it here. When I'm not writing code for work, I occasionally write code for fun. You can see an example or two at http://www.faustware.com. And I occasionally blog at http://www.tomfaust.com.

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAnurag Gandhi14-Jun-12 2:12 
QuestionGood work, this is the only working example on the internet Pinmemberspyhunter99931-Jan-12 10:17 
GeneralGreat Job.... PinmemberSrinu_ss512-Mar-11 4:23 
Questionany updates ?? Pinmemberalhambra-eidos10-Feb-11 4:30 
GeneralStart/Stop IIS server for IIS 5.1 PinmemberMikeSharp19-Aug-09 6:34 
GeneralRe: Start/Stop IIS server for IIS 5.1 PinmemberTom Faust19-Aug-09 12:38 
GeneralmanagementObjectSearcher.Get() exception Pinmembersukupinny17-Aug-09 20:05 
GeneralRemote Server + Different credentials Pinmembernbissette26-Nov-08 7:07 
QuestionHow to detect one of IIS Pool is Stop? Pinmemberk_homayouni14-Sep-08 9:40 
QuestionError in managementObjectSearcher.Get() PinmemberSheel07029-Sep-08 11:07 
AnswerRe: Error in managementObjectSearcher.Get() Pinmemberalexanderdev17-Mar-09 0:04 
GeneralDoes not work when used on remote machines PinmemberMember 344944229-Aug-08 12:01 
GeneralRe: Does not work when used on remote machines Pinmemberanava13-Apr-09 12:25 
Review the RPC service in the control panel -> Administrative tools -> Services
the RPC (Remote Procedure calls) service needs be running (start)
QuestionHow it works for Remote IIS Pinmembersqzaman28-Mar-08 16:32 
Questionsom management object queries does not retrives result. Pinmembershivamraj26-Nov-07 23:31 
QuestionOption? Pinmembermerlin9811-Nov-07 4:06 
AnswerRe: Option? PinmemberTom Faust1-Nov-07 4:58 
GeneralShared Hosting Pinmembersameeraperera31-Oct-07 17:04 
GeneralRe: Shared Hosting PinmemberTom Faust31-Oct-07 18:40 
GeneralRe: Shared Hosting Pinmembersameeraperera31-Oct-07 18:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140821.2 | Last Updated 31 Oct 2007
Article Copyright 2007 by Tom Faust
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid