从应用程序的物理路径中停止应用程序池 - ServerManager C#

时间:2016-02-05 16:09:56

标签: c# asp.net c#-4.0 iis-7 servermanager

使用ServerManager类是否可以从应用程序的物理路径中获取应用程序池名称?我一直在测试以下代码:

using (var manager = new ServerManager())
//using (var manager = ServerManager.OpenRemote("xxx")) //Uncomment this line to enable remote debugging, comment out line 1821, update Server Name value
{
    //Get Site using Website ID
    var site = manager.Sites.SingleOrDefault(m => m.Id == webSiteID);

    if (site != null)
    {
        //foreach (Application app in site.Applications)
        //{
            bld.AppendLine("1. Stopping App Pool for: " + site.Name);
            //Get the application pool name
            var application = site.Applications.SingleOrDefault(m => m.VirtualDirectories["/"].PhysicalPath == @"D:/inetpub/TestSite1"); //RETURNS NULL
            //Get the application binded to the siteName
            var application1 = site.Applications.SingleOrDefault(m => m.Path == "/TestSite1"); //RETURN INFO I REQUIRE

            var appPoolName = application.ApplicationPoolName;
            //var appPoolName = site.Applications.FirstOrDefault().ApplicationPoolName;
            var appPool = manager.ApplicationPools[appPoolName];

            if (appPool != null)
            {
                //Check the App Pool State
                if (appPool.State == ObjectState.Stopped)
                {
                    //App Pool already stopped
                    bld.AppendLine("1. App Pool: " + appPool.Name + " already stopped.");
                }
                else
                {
                    //Stop the App Pool
                    appPool.Stop();
                    bld.AppendLine("1. App Pool: " + appPool.Name + " stopped.");
                }
            }
            else
            {
                bld.AppendLine("1. No App Pool found.");
                failFlag = true;
            }                            
        //}                        
    }
    else
    {
        bld.AppendLine("1. SiteID: " + webSiteID + " does not exist.");
        failFlag = true;
    }
}

}

我想使用物理路径来获取应用程序而不是虚拟路径,因为我的应用程序数据库中有数百个应用程序,我不能100%表示他们已经在IIS中配置了所有应用程序。 2个路径将同步,例如D:\ inetpub \ TestSite1和/ TestSite1

1 个答案:

答案 0 :(得分:0)

在这行代码中将fwd斜杠更改为反斜杠似乎对我有用了:

var application = site.Applications.SingleOrDefault(m => m.VirtualDirectories["/"].PhysicalPath == @"D:\inetpub\TestSite1");

在我的代码中,我现在使用参数而不是硬编码物理路径,所以我有这样的东西:

using (var manager = new ServerManager())                
{
   //Get Site using Website ID
   var site = manager.Sites.SingleOrDefault(m => m.Id == webSiteID);

   if (site != null)
   {
      bld.AppendLine("1. Stopping App Pool for: " + site.Name + " " + targetPath);
      var application = site.Applications.SingleOrDefault(m => m.VirtualDirectories["/"].PhysicalPath == @targetPath);
      var appPoolName = application.ApplicationPoolName;
      var appPool = manager.ApplicationPools[appPoolName];
      if (appPool != null)
      { ...

希望将来帮助其他人。