我遇到C#问题,需要帮助。
我创建了一个包含IP地址和端口对的文本文件;每行一对。它的结构是这样的:
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(":");
我尝试了很多方法,但我无法修复它。
提前致谢。
答案 0 :(得分:2)
您对sr.ReadLine()
的调用最有可能返回null,使str_2
为null,并导致str_2.IndexOf
抛出异常。
您有2次致电.ReadLine()
。你实际阅读了多少行数据?如果只有一行,则第二次调用将返回null,从而导致上述行。