Mark
Mark

Reputation: 197

Stopping IIS in C#

I am using C# to automate some procedures

  1. Start IIS
  2. Open Internet Explorer at a specific address on specific port
  3. User closes the browser
  4. Stop IIS

I am stuck on step four as I have to use the same port for other procedures after.

I created a thread that will be called to start IIS:

public class MyThread
{
    //thread to start IIS
    public static void Thread1()
    {
        //thread for running IIS
        using (Process proc = new Process())
        {
            proc.StartInfo.FileName = @"C:\Program Files\IIS Express\iisexpress.exe";
            proc.StartInfo.Arguments = @"/path:""c:\windows\Microsoft.NET\Framework\v4.0.30319\ASP.NETWebAdminFiles"" /vpath:/asp.netwebadminfiles /port:61569 /clr:4.0 /ntlm";
            //proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.Start();
            proc.WaitForExit(); 
            //output from the process run
            Console.Out.WriteLine(proc.StandardOutput.ReadToEnd());
        }
    }
}

The code to open IE is:

Thread thread1 = new Thread(new ThreadStart(MyThread.Thread1));
        thread1.Start();
        using (Process proc1 = new Process())
        {
            proc1.StartInfo.FileName = @"C:\Program Files\Internet Explorer\iexplore.exe";
            proc1.StartInfo.Arguments = @"http://localhost:61569/asp.netwebadminfiles/default.aspx?applicationPhysicalPath=C:\Users\"+userName+@"\Documents\Visual Studio 2013\Projects\NN\&applicationUrl=/";
            proc1.StartInfo.UseShellExecute = false;
            proc1.StartInfo.RedirectStandardOutput = true;
            proc1.StartInfo.CreateNoWindow = true;
            proc1.Start();
            proc1.WaitForExit();
            //output from the process run
            Console.Out.WriteLine(proc1.StandardOutput.ReadToEnd());
        }

I have tried to create another thread to Kill/Abort the original thread, but that doesn't work. I also tried to write "Q" at the end of the console, but that also does nothing.

Any ideas of how I can stop IIS when the browser is closed?

Upvotes: 1

Views: 515

Answers (1)

Ananke
Ananke

Reputation: 1230

You shouldn't be killing the process to stop IIS. Pulling the rug underneath it isn't a great thing to do, and besides, if the service has any restart actions then it will start right back up again.

Use a ServiceController (http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller(v=vs.110).aspx) to start and stop the appropriate service.

There are other ways to control IIS such as using WMI (which I believe is now deprecated), however using a ServiceController should be sufficient for your task.

Upvotes: 2

Related Questions