在C#中停止和启动IIS [英] Stopping and Starting IIS in C#
问题描述
我需要能够在C#中启动/停止IIS.我的经理已负责创建此模块.以下是我的尝试:
I need to be able to Start/Stop the IIS in C#. I've been tasked with creating this module by my manager. The following is my attempt:
ServiceController service = new ServiceController("w3svc");
service.Stop();
我遇到以下异常:
无法在计算机."上打开w3svc服务.
Cannot open w3svc service on computer '.'.
我正在编写代码来停止本地计算机上的IIS.
I am writing the code to stop the IIS on the local machine.
我也尝试使用IISAdmin
作为服务名,但是在我的计算机上找不到IISAdmin
.
I also tried IISAdmin
as the servicename, but IISAdmin
could not be found on my computer.
推荐答案
您必须使用
Microsoft.Web.Administration(MWA)API被构建为托管
应用程序主机管理API(AHADMIN)上的代码包装
这是一个本机代码接口库.它提供了程序化
访问和更新Web服务器配置的方式以及
管理信息.
The Microsoft.Web.Administration (MWA) APIs are built as a managed
code wrapper over the Application Host Administration API (AHADMIN)
which is a native code interface library. It provides a programmatic
way to access and update the web server configuration and
administration information.
此文章讨论了有关以下内容的详细方案使用Microsoft.Web.Administration. This article discuss detailed scenarios for using Microsoft.Web.Administration. 请注意,您必须以管理员身份运行C#应用程序才能在IIS上执行任何操作.否则,您可能会被拒绝访问. 这篇关于在C#中停止和启动IIS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
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();
//start the site
site.Start();
}
}
}