2016-01-23 12 views
0

在C#中創建遠程安裝程序應用程序。首先,我正在執行ping檢查以確保計算機在我運行安裝之前已經存在。我將在稍後執行服務檢查。創建一個字符串數組以稍後在C#中調用

我需要創建一個字符串數組,它將基於ping狀態是成功(goodPing)和失敗(badPing),所以我可以在安裝將運行的另一個foreach循環中使用它。

foreach (string singleComputer in computerArray) 
     { 
      // Ping all computers 
      Ping ping = new Ping(); 
      PingReply pingresult = ping.Send(singleComputer); 

      if (pingresult.Status.ToString() == "Success") 
      { 
       string[] goodPing = new string[] {"singleComputer"}; 
      } 
      else if (pingresult.Status.ToString() != "Success") 
      { 
       string[] badPing = new string[] {"singleComputer"}; 
      } 
     } 

基本上,我確信計算機是可以ping通的,將「好」和「壞」計算機分開。 computerArray是從文件創建的字符串數組。

這就是我想要的樣子後,我創建數組:

foreach (string computer in goodPing) 
{ 
    //run installation code here. 
} 

很顯然,我不能叫goodPing因爲它是在一個if語句創建。請告訴我我做錯了什麼。

回答

2

在運行循環之前,您需要創建一次數組。數組的問題在於沒有簡單的方法來改變數組的大小,並且事先並不知道每個數組中有多少條記錄。所以,我建議使用List<T>代替陣列:

List<string> goodPing = new List<string>(); 
List<string> badPing = new List<string>(); 
Ping ping = new Ping(); 

foreach (string singleComputer in computerArray) 
{ 
    // Ping all computers 
    PingReply pingresult = ping.Send(singleComputer); 

    if (pingresult.Status.ToString() == "Success") 
    { 
     goodPing.Add(singleComputer); 
    } 
    else if (pingresult.Status.ToString() != "Success") 
    { 
     badPing.Add(singleComputer); 
    } 
} 

現在你可以使用良好的偵測的列表,你需要做什麼:

foreach (string computer in goodPing) 
{ 
    //run installation code here. 
} 
+0

使用此方法有什麼缺點嗎?你知道嗎? –

+0

我很欣賞快速反應。 –

+0

@JulianJohnson不知道我是否理解這個缺點。你是否意味着在循環之前創建變量的缺點? – dotnetom

0

您需要使用泛型列表,而不是陣列你需要在for循環之前聲明它們,以便它們在後面可以被訪問。

List<string> goodPings = new List<string>(); 
List<string> badPings = new List<string>(); 
foreach (string singleComputer in computerArray) 
     { 
      // Ping all computers 
      Ping ping = new Ping(); 
      PingReply pingresult = ping.Send(singleComputer); 

      if (pingresult.Status.ToString() == "Success") 
      { 
       goodPings.Add(singleComputer); // and don't forget to use the variable singleComputer here, not the literal string "singleComputer". 
      } 
      else if (pingresult.Status.ToString() != "Success") 
      { 
       badPings.Add(singleComputer); 
      } 
     } 
相關問題