2012-10-04 24 views
0

我目前能夠檢測到IIS網站是否啓動/暫停/使用下面的代碼停止:檢測IIS網站被停用

public int GetWebsiteStatus(string machineName, int websiteId) 
{ 
    DirectoryEntry root = new DirectoryEntry(
     String.Format("IIS://{0}/W3SVC/{1}", machineName, websiteId)); 
    PropertyValueCollection pvc = root.Properties["ServerState"]; 
    return pvc.Value 
    // - 2: Website Started 
    // - 4: Website Stopped 
    // - 6: Website Paused 
} 

我也想,如果一個網站被暫停或不檢測。如果網站被暫停,上面的方法仍然返回2(這是正確的),但對我來說還不夠。

我找不到任何代碼可以完成IIS6及更高版本的工作。

+0

你的意思是說暫停它時不會返回6嗎? – cirrus

+0

「暫停」是什麼意思?你可以在IIS中暫停一個網站,但你的意思是不同的? – Clafou

+1

@cirrus暫停是網站的狀態,如已啓動和已停止。暫停是一種開始的子狀態。如果我暫停網站,我會收到狀態6,這樣就可以。但是如果網站在20分鐘內不使用,IIS將暫停網站。如果您再次請求該網站,它會醒來。因此,上述方法返回2是正確的,因爲該網站處於活動狀態但已暫停。 – hwcverwe

回答

3

啊,你的意思是應用程序池由於超時配置而停止了嗎?這是一個不同的網站記得的狀態?那麼,當然,你可以改變設置,使其不會回收,但你也可以嘗試使用這樣的代碼;

首先,添加對\ Windows \ System32 \ inetsrv \ Microsoft.Web.Administration.dll的引用,然後;

using System; 
using System.Collections.Generic; 
using System.Text; 
using Microsoft.Web.Administration; 
namespace MSWebAdmin_Application 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      ServerManager serverManager = new ServerManager(); 
      Site site = serverManager.Sites["Default Web Site"]; 

      // get the app for this site 
      var appName = site.Applications[0].ApplicationPoolName; 
      ApplicationPool appPool = serverManager.ApplicationPools[appName]; 

      Console.WriteLine("Site state is : {0}", site.State); 
      Console.WriteLine("App '{0}' state is : {1}", appName, appPool.State); 

      if (appPool.State == ObjectState.Stopped) 
      { 
       // do something because the web site is "suspended" 
      } 
     } 
    } 
} 

該代碼將獨立地檢查appPool的狀態,而不是您的網站。網站可以返回「開始」,appPool返回「已停止」。

看看它是否適用於你的情況。

+0

如果appPool.State完全停止,則它僅返回「已停止」。因此,檢查appPool.State將不起作用,因爲它總是返回'Started'。但改變檢查有點幫助我。我已經改變了如果這樣if(appPool.WorkerProcesses.Count == 0){/ * suspended * /}'。所以謝謝你的回答:) – hwcverwe

1

您可能想嘗試使用以下代碼,添加您自己的邏輯並整理當然......但實質上您需要執行以下操作並根據需要修改代碼。

添加以下枚舉

public enum ServerState 
     { 
      Unknown = 0, 
      Starting = 1, 
      Started = 2, 
      Stopping = 3, 
      Stopped = 4, 
      Pausing = 5, 
      Paused = 6, 
      Continuing = 7 
     } 

搜索網站並進行處理...

DirectoryEntry w3svc = new DirectoryEntry("IIS://" + "localhost" + "/W3SVC"); 
//check each site 
foreach (DirectoryEntry site in w3svc.Children) 
{ 
    foreach (var s in site.Properties) 
    { 
     try 
     { 
      ServerState state = 
       (ServerState) 
       Enum.Parse(typeof (ServerState), site.Properties["ServerState"].Value.ToString()); 

      if (state == ServerState.Paused) 
      { 
       //Do action 
      } 
     } 
     catch (Exception) 
     { 

     } 

    } 
} 

我希望這是對你來說也是有用......

http://csharp-tipsandtricks.blogspot.co.uk/2009_12_01_archive.html