问题
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]));"
The exception is
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]));
}
回答1:
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
.
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]));
}
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();
回答2:
You were trying to add a value which was not an IP address.
I would suggest to use TryParse. Then if the function returns false
you know there was an invalid value and you could show a message showing the invalid value.
来源:https://stackoverflow.com/questions/23449646/ip-address-exception-when-adding-to-a-list-in-c-sharp