Вопрос

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]));
        }
Это было полезно?

Решение 2

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top