转《IIS 7管理API——Microsoft.Web.Administration介绍 》
Microsoft中提供了管理IIS7的一些非常强大的API——Microsoft.Web.Administration,可以很方便的让我们以编程的方式管理,设定IIS 7的各项配置。Microsoft.Web.Administration.dll位于IIS的目录(%WinDir%\System32\InetSrv)下,在项目中添加对其的引用后您就可以使用这些API了。下图显示了Microsoft.Web.Administration.dll中的主要对象。
让我们通过几个例子来使用Microsoft.Web.Administration,下面的例子均非常易懂,我就不再过多解释了。
建立一个站点(Site)
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.Update();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.Update();
将一个应用程序(Application)添加到一个站点
ServerManager iisManager = new ServerManager();
iisManager.Sites["NewSite"].Applications.Add("/Sales", "d:\\MyApp");
iisManager.Update();
iisManager.Sites["NewSite"].Applications.Add("/Sales", "d:\\MyApp");
iisManager.Update();
建立一个虚拟目录(Virtual Directory)
ServerManager iisManager = new ServerManager();
Application app = iisManager.Sites["NewSite"].Applications["/Sales"];
app.VirtualDirectories.Add("/VDir", "d:\\MyVDir");
iisManager.Update();
Application app = iisManager.Sites["NewSite"].Applications["/Sales"];
app.VirtualDirectories.Add("/VDir", "d:\\MyVDir");
iisManager.Update();
运行时控制:停止一个站点
ServerManager iisManager = new ServerManager();
iisManager.Sites["NewSite"].Stop();
iisManager.Sites["NewSite"].Stop();
运行时控制:回收应用程序池(Recyciling an Application Pool)
ServerManager iisManager = new ServerManager();
iisManager.ApplicationPools["DefaultAppPool"].Recycle();
iisManager.ApplicationPools["DefaultAppPool"].Recycle();
运行时控制:得到当前正在处理的请求
ServerManager iisManager = new ServerManager();
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses) {
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests(0)) {
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}
foreach(WorkerProcess w3wp in iisManager.WorkerProcesses) {
Console.WriteLine("W3WP ({0})", w3wp.ProcessId);
foreach (Request request in w3wp.GetRequests(0)) {
Console.WriteLine("{0} - {1},{2},{3}",
request.Url,
request.ClientIPAddr,
request.TimeElapsed,
request.TimeInState);
}
}
还有一个有用之处是Microsoft.Web.Administration提供了对*.config(例如web.config)文件的编辑功能,让您再也不用像修改普通XML文件一样修改*.config了
以上代码要不完全对,要进行修改才能使用!
原文地址:http://dflying.cnblogs.com/archive/2006/04/17/377276.html