2017-10-11 8 views
0

첫 번째 앱 중 하나를 쓰고 있는데 문제가 발생했습니다. 내 foreach 루프가 종료 된 후 연결할 수없는 주소를 입력하면 내 앱이 중단 모드로 전환되지만 foreach가 결과를 얻으면 정상적으로 진행됩니다.SendPingAsync는 모든 호스트에 연결할 수없는 경우 중단 모드로 전환합니다. C#

이 예외가 발생합니다 코드의 일부입니다

예외가 발생합니다 : 'System.ArgumentOutOfRangeException이를'mscorlib.dll에 에

private async void Button_Click(object sender, RoutedEventArgs e) 
{ 
    /// Verify that input box is not blank 
    if (string.IsNullOrWhiteSpace(inputBox.Text)) 
    { 
     MessageBox.Show("Cannot be left blank !", "Error"); 
     return; 
    } 

    /// Creates a list of Gateway options to try from 
    string[] gatewayArray = { "cadg0", "frdg0", "dedg0", "gbdg0", "iedg0", "usdg0", "dg", "dg0" }; 

    /// Specifies where to get store number from 
    string storeNumber = inputBox.Text; 
    string pingReply; 
    string pingStatus; 

    clearButton_Click(sender, e); 

    Ping ping = new Ping(); 

    foreach (string gateway in gatewayArray) 
     try 
     { 
      /// Replace store number with "Wait" text and changes color of box to red. 
      inputBox.Text = "Please Wait..."; 
      inputBox.Background = Brushes.Red; 

      /// Pings selected store using Async method 
      PingReply reply = await ping.SendPingAsync(gateway + storeNumber, 2000); 

      pingReply = reply.Address.ToString(); 
      pingStatus = reply.Status.ToString(); 

       /// Displays results of Ping 
       ipOne.Clear(); 
       ipOne.Text = pingReply; 
       statusOne.Clear(); 
       statusOne.Text = pingStatus; 
       if (statusOne.Text == "Success") 
       { 
        statusOne.Text = "- ONLINE -"; 
        statusOne.Background = Brushes.LightGreen; 
       } 
       else 
       { 
        statusOne.Background = Brushes.Orange; 
       } 

       /// Get name of host 
       IPHostEntry ipHostOne = Dns.GetHostEntry(pingReply); 
       string ipOneName = ipHostOne.HostName; 
       ipOneName = ipOneName.Substring(0, ipOneName.LastIndexOf(".") - 10); 
       nameOne.Text = ipOneName.ToUpper(); 

      } 

      catch (ArgumentOutOfRangeException ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 

      catch (PingException) 
      { 
       /// Catches exceptions and continues 
       /// MessageBox.Show("Unreachable !"); 
      } 

것은 내가 얻을 잘못된 점 번호를 지정하는 경우를 처리되지 않은 'System.ArgumentOutOfRangeException'형식의 예외가 발생했습니다. in mscorlib.dll StartIndex는 0보다 작을 수 없습니다.

The program '[19616] SbPinger.exe' has exited with code -1 (0xffffffff). 

나는 시도/캐치로 처리하려고 : 캐치는 아무것도하지 않고 프로그램이 여전히 모드 브레이크 들어간다 그러나

catch (ArgumentOutOfRangeException ex) 
{ 
    MessageBox.Show(ex.Message); 
} 

.

내 프로그램은 가능한 모든 기본 게이트웨이를 핑 (ping)하고 IP가 해당 IP를 찾으면 IP를 반환 한 다음 해당 네트워크에서 개별 PC를 핑합니다. Ping이 게이트웨이에 도달하지 않는 경우를 제외하고는 다른 모든 기능이 작동합니다. C#을 불과 몇 주간 사용하면서 제게 쉽게가주십시오. 어떤 도움이라도 대단히 감사하겠습니다.

피터

+0

'string.IsNullOrWhiteSpace'는 문자열이 비어 있는지 검사하기 때문에'inputBox.Text == ""'는 중복됩니다. 또한 처음부터 * null인지 확인해야하기 때문에 여기도 잘못되었습니다. 즉, 여기에 예외 호출 스택도 게시해야합니다. – Clemens

+0

감사합니다. 나머지 Try/catch 코드도 추가했습니다. –

+0

호출 스택은 어떻습니까? 그리고'ipOneName.Substring (0, ipOneName.LastIndexOf (".") - 10)'은 의심 스럽습니다. 당신은 항상'.'이 있고 그 위치는 처음부터 최소한 10 자라고 확신합니까? – Clemens

답변

0

내가 찾은 그래서 다른 일을 잠시 둘러보고 및 시도 후 모든 프로세스가 완료 년부터 충돌하지 않는 Dns.GetHostEntry를 사용하는 대신 URL 핑, 수율 훨씬 더 빨리 결과를 그. 관심있는 사람은 다음 코드를 참조하십시오.

// Get IP from DG adrress 
      try 
      { 
       IPHostEntry hostEntry = Dns.GetHostEntry("URL"); 
       IPAddress[] address = hostEntry.AddressList; 
       textBox.Text = address.GetValue(0).ToString(); 
      } 
      catch 
      { 
       // Catches Exception and moves on 
       // MessageBox.Show("No result", "Error"); 
      } 

감사합니다.