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]));
}
You were trying to add a value which was not an IP address.
I would suggest to use
TryParse
. Then if the function returnsfalse
you know there was an invalid value and you could show a message showing the invalid value.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 byIPAddress.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.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):