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();