在C#中添加到列表时的IP地址异常 [英] IP address exception when adding to a list in C#
问题描述
我正在尝试从文本文件中读取一组IP,并将其添加到IPAddress类型列表中.在"listIPAdrrs.Add(IPAddress.Parse(list [i]));"行上引发了异常.
I am trying to read a set of IPs from a text file and add it to a IPAddress type list. An exception is raised on the line "listIPAdrrs.Add(IPAddress.Parse(list[i]));"
例外是
指定了无效的IP地址.
An invalid IP address was specified.
List<string> list = new List<string>();
string text = System.IO.File.ReadAllText(@"D:\ips.txt");
String[] str = text.Split('\n');
for (int j = 0; j < str.Length; j++)
{
list.Add(str[j]);
}
List<IPAddress> listIPAdrrs = new List<IPAddress>();
for (int i = 0; i < list.Count; i++)
{
//Console.WriteLine(list[i]);
listIPAdrrs.Add(IPAddress.Parse(list[i]));
}
推荐答案
问题是,行尾不一定只是\n
(在Windows中,很可能是\r\n
),并且IP地址后面是IPAddress.Parse
认为\r
字符不是有效的IP地址.
The problem is that line endings are not necessarily just a \n
(on Windows, it's most likely \r\n
), and an IP address followed by the \r
character isn't considered a valid IP address by IPAddress.Parse
.
幸运的是,进行CLR的人员认为这一切并得到了一些非常强大的代码,因此我们将改用File.ReadAllLines
.
Fortunately, the guys who made the CLR thought it all out and got some pretty robust code, so we're going to use File.ReadAllLines
instead.
List<string> list = new List<string>(System.IO.File.ReadAllLines(@"D:\ips.txt"));
List<IPAddress> listIPAdrrs = new List<IPAddress>();
for (int i = 0; i < list.Count; i++)
{
//Console.WriteLine(list[i]);
listIPAdrrs.Add(IPAddress.Parse(list[i]));
}
如果这是您的事,您还可以使用LINQ使其更短(尽管您失去了使用TryParse
的能力):
If that's your kind of thing, you can also use LINQ to make it even shorter (though you lose the ability to use TryParse
doing it):
List<IPAddress> listIPAdrrs = System.IO.File.ReadAllLines(@"D:\ips.txt")
.Select(line => IPAddress.Parse(line))
.ToList();
这篇关于在C#中添加到列表时的IP地址异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!