Click here to Skip to main content
15,860,943 members
Articles / Programming Languages / C#
Article

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

Rate me:
Please Sign up or sign in to vote.
4.57/5 (14 votes)
31 Oct 2007CPOL2 min read 145.5K   6.5K   57   22
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.

C#
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.

C#
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.

C#
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.

C#
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)


Written By
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

 
QuestionError in managementObjectSearcher.Get() Pin
Sheel07029-Sep-08 11:07
Sheel07029-Sep-08 11:07 
AnswerRe: Error in managementObjectSearcher.Get() Pin
alexanderdev17-Mar-09 0:04
alexanderdev17-Mar-09 0:04 

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

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