2011-12-11 10 views
-2

私はC#に問題があり、助けが必要です。このエラーを解決するには:nullreferenceexceptionが処理されていません

IPアドレスとポートのペアを含むテキストファイルを作成しました。 1行に1組。構造は次のとおりです。

xxx.xxx.xxx.xxx:xxxx 
xxx.xxx.xxx.xxx:xxxx 
xxx.xxx.xxx.xxx:xxxx 

これはコードです。

public void Filter() 
     { 
      // Read proxy from text file 

      string ppath = @"C:\Program Files\HTE\IP.txt"; 
      StreamReader sr = new StreamReader(ppath); 

      /* 
      Proxies in the text file have a contruction like this: xxx.xxx.xxx.xxx:xxxx 
      It includes more than 11k proxies 
      Now start to collect ip 
      */ 

      for (int i = 0; i < 11000; i++) 
      { 
       if (i > 0) 
       { 
        // Create a loop to ignore the line(s) which has been filter 

        for (int j = 0; j < i; j++) 
        { 
         // When j = 0, that mean it has an ignore line 

         sr.ReadLine(); 
         GC.Collect(); 
        } 

        // Read new line 

        string str_2 = sr.ReadLine(); 
        int position_2 = str_2.IndexOf(":"); 

        // Get ip 

        string str_ip_2 = str_2.Substring(0, position_2); 
        int tail_2 = str_2.Length - position_2; 
        string str_tmp_2 = str_2.Substring(position_2, tail_2); 
        int subtraction_2 = str_tmp_2.Length - 1; 

        // Get port 

        string str_port_2 = str_tmp_2.Substring(1, subtraction_2); 
        GC.Collect(); 
       } 
       else if (i == 0) 
       { 
        string str = sr.ReadLine(); 

        // find ":" in the postion of the first line 

        int position = str.IndexOf(":"); 

        // Get ip 

        string str_ip = str.Substring(0, position); 

        // The tail of string in line is proxy port 

        int tail = str.Length - position; 
        string str_tmp = str.Substring(position, tail); 
        int subtraction = str_tmp.Length - 1; 

        // Get port 

        string str_port = str_tmp.Substring(1, subtraction); 
        GC.Collect(); 
       } 
      } 

エラーコード:

string str_2 = sr.ReadLine(); 
int position_2 = str_2.IndexOf(":"); 

私は多くの方法を試してみましたが、私はそれを修正することができませんでした。

ありがとうございます。

答えて

2

sr.ReadLine()への呼び出しはnullを返し、str_2をヌルにし、str_2.IndexOfが例外をスローする可能性があります。

.ReadLine()に2回の呼び出しがあります。実際に何行のデータを読み込んでいますか? 1行だけの場合、2番目の呼び出しはnullを返し、上記を引き起こします。

関連する問題