Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.
using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;
public static class IisExpress
{
#region Parameters
public static string SiteFolder = @"C:\temp\UE_Soln_7\Spc.Frm.Imp";
public static uint Port = 3001;
public static int ProcessStateChangeDelay = 10 * 1000;
public static string IisExpressExe = @"C:\Program Files (x86)\IIS Express\iisexpress.exe";
#endregion
public static void Start()
{
Process.Start(InvocationInfo);
Thread.Sleep(ProcessStateChangeDelay);
}
public static void Stop()
{
var p = GetWin32Process();
if (p == null) return;
var pp = Process.GetProcessById((int)p.ProcessId);
if (pp == null) return;
pp.Kill();
Thread.Sleep(ProcessStateChangeDelay);
}
public static bool IsStarted()
{
var p = GetWin32Process();
return p != null;
}
static readonly string ProcessName = Path.GetFileName(IisExpressExe);
static string Quote(string value) { return "\"" + value.Trim() + "\""; }
static string CmdLine =
string.Format(
@"/path:{0} /port:{1}",
Quote(SiteFolder),
Port
);
static readonly ProcessStartInfo InvocationInfo =
new ProcessStartInfo()
{
FileName = IisExpressExe,
Arguments = CmdLine,
WorkingDirectory = SiteFolder,
CreateNoWindow = false,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Minimized
};
static Win32Process GetWin32Process()
{
//the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
using (var mo = new ManagementObjectContext())
foreach (var p in mo.CIMv2.Win32Processes)
if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
return p;
return null;
}
}