从文本文件中读取 ip:port 并在我的字符串中使用它并在代码中将 ip 与端口区分为“:”的最佳方法
Best way to read ip:port from a text file and use this in my string and differentiate ip from port as ":" in code
string ip;
int port;
这是我读入文本文件的代码 IEnumerable<String> lines = File.ReadLines("proxies.txt");
我想通过从文本文件中读取它们作为 IP:PORT 来对代码(上面)中的 IP 和 PORT 进行排序,并将它们用于我的 string/int.我想即时访问它们。
一次只能使用一个IP:PORT。(我猜它们可以是数组的一部分,如[0],每次循环时每行加1)
列表文件非常简单,这是一个可视化
ip1:port1
ip2:port2
ip3:port3
ip4:port4
阅读第一行(现在;我将保留 read-all-lines 代码,以便您将来可以选择不同的行,但如果您的文件很大,请参阅下面的补充内容)并将其拆分在冒号上,将第一位作为ip,第二位作为端口:
string[] lines = File.ReadAllLines("path");
string[] bits = lines[0].Split(':');
string host = bits[0];
int port = int.Parse(bits[1]);
这里没有错误处理 - 如果文件有零行,或者如果第一行没有冒号,或者如果冒号后面的数据不是数字,你会得到一个异常..
如果您的文件很大,使用 ReadLines() 可能会更好,因为它不会一次读取整个文件;当您从中拉出时,它会逐渐读取。像这样:
IEnumerable<string> lines = File.ReadLines("path");
string[] bits = lines.First().Split(':');
string host = bits[0];
int port = int.Parse(bits[1]);
在这里你可以循环文本中的所有行。
string line;
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\test.txt");
while ((line = file.ReadLine()) != null)
{
var data = line.Split(':');
string ipAdd = data[0];
int port = int.Parse(data[1]);
//Your conditions here...
Console.WriteLine(ipAdd);
Console.WriteLine(port);
}
string ip;
int port;
这是我读入文本文件的代码 IEnumerable<String> lines = File.ReadLines("proxies.txt");
我想通过从文本文件中读取它们作为 IP:PORT 来对代码(上面)中的 IP 和 PORT 进行排序,并将它们用于我的 string/int.我想即时访问它们。
一次只能使用一个IP:PORT。(我猜它们可以是数组的一部分,如[0],每次循环时每行加1) 列表文件非常简单,这是一个可视化
ip1:port1
ip2:port2
ip3:port3
ip4:port4
阅读第一行(现在;我将保留 read-all-lines 代码,以便您将来可以选择不同的行,但如果您的文件很大,请参阅下面的补充内容)并将其拆分在冒号上,将第一位作为ip,第二位作为端口:
string[] lines = File.ReadAllLines("path");
string[] bits = lines[0].Split(':');
string host = bits[0];
int port = int.Parse(bits[1]);
这里没有错误处理 - 如果文件有零行,或者如果第一行没有冒号,或者如果冒号后面的数据不是数字,你会得到一个异常..
如果您的文件很大,使用 ReadLines() 可能会更好,因为它不会一次读取整个文件;当您从中拉出时,它会逐渐读取。像这样:
IEnumerable<string> lines = File.ReadLines("path");
string[] bits = lines.First().Split(':');
string host = bits[0];
int port = int.Parse(bits[1]);
在这里你可以循环文本中的所有行。
string line;
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\test.txt");
while ((line = file.ReadLine()) != null)
{
var data = line.Split(':');
string ipAdd = data[0];
int port = int.Parse(data[1]);
//Your conditions here...
Console.WriteLine(ipAdd);
Console.WriteLine(port);
}