用asp.net来回收IIS6.0应用程序池

网站由于使用比较多的缓存,有时会出现缓存错误,导致程序异常,这个时候需要回收一个应用程序池就可以了。
以前每次都是通过远程桌面连接到服务器,然后在应用程序池上右击》回收,感觉比较麻烦,于时找了如下的一个办法来实现。
其实就是普通的一个asp.net页面,加上一个按钮,进行回收,主要程序如下:
 1 
 2     protected void StartStopRecycleApp(string method)
 3     {
 4         string AppPoolName = this.tbAppName.Text.Trim();
 5         //string method = "Recycle";
 6 
 7         try
 8         {
 9             DirectoryEntry appPool = new DirectoryEntry("IIS://localhost/W3SVC/AppPools");
10             DirectoryEntry findPool = appPool.Children.Find(AppPoolName, "IIsApplicationPool");
11             findPool.Invoke(method, null);
12             appPool.CommitChanges();
13             appPool.Close();
14             lbMsg.Text = string.Format("应用程序池{0}{1}成功", AppPoolName,method);
15         }
16         catch (Exception ex)
17         {
18             lbMsg.Text = string.Format("应用程序池{0}{2}失败:{1}", AppPoolName, ex.Message,method);
19         }
20     }

tbAppName是一个textbox,用来输入应用程序池的名字,如“DefaultAppPool”。
当method="Recycle"时就是回收,为“Start”时是启动,为“Stop”时是停止。

注意:
1. 必须引入System.DirectoryServices包
2. 运行此程序的应用程序也的用户必须权限比较高,可以单独为此程序提供应用程序程,或者建立一个虚拟目录在配制里模拟高级用户(如administrators或者system),否则应用程序会抛出“拒绝访问”的异常。
posted @ 2008-11-12 23:41  canbeing  阅读(1556)  评论(4编辑  收藏  举报