I would like to send data from a txt(read) file to a listbox

Asked

Viewed 19 times

0

For example:

File reading

string [] linhas = File.ReadAllLines("ip.txt");
Console.ReadLine();  

I did the file reading, now I want to throw them in a ListBox, how to do?

  • You are using Forms?

  • yes. windows form, I managed to read a file, now I want to send it to listbox

  • what has each line of the txt file?

  • IP’s 200.135.80.9, I will try before sending to listbox, validate whether the ip is valid or not

  • each line is an IP? how is this txt formatted?

  • each line is an ip, there are valid ips and ones not, I need to validate and send to listbox validates or invalidates for example : 200.135.80.9 192.168.1.1 8.35.67.74
257.32.4.5
85.345.1.2
1.2.3.4
9.8.234.5
192.168.0.256

  • You want in the question a thing has no validation, as it is validating?

  • I will explain in detail, I need to read the txt file, validate whether the ip is valid or not, and send it to a listbox :Ipaddress ipAddr; string addr = " 200.135.80.9"; bool res = Ipaddress.Tryparse(addr, out ipAddr); if (res) Console.Writeline("valid ip"); Else Console.Writeline(" ip Invalid");

Show 3 more comments

1 answer

0


Basically to read a text file where each line represents a number ip and add in a Listbox is simple:

using (StreamReader str = new StreamReader("ip.txt"))
{
    string item = string.Empty;
    while ((item = str.ReadLine()) != null)
    {
        if (IPAddress.TryParse(item, out _))
        {
            listBox1.Items.Add(item);
        }
    }
}

Note: the structure you are using has low performance and as you will need to iterate in each line the best way is this, making within the own reading the addition, saves memory and increases performance.

  • 1

    Man, thank you very much, it worked out what I asked, you know any function I can validate if the ip is valid or not? are two listbox, valid ip and invalid ip

  • @Matheusbatista made the change with the validation and the discard where only need the text value.

  • Thank you very much, thank you very much... how can I repay you? I never thought that anyone could help so much.

  • @Matheusbatista only when creating a question put all the details in the question itself and be clear, when you accept the question and click the up arrow is already helping the community.

  • No @Matheusbatista here is to help even ... rest assured

  • 1

    Thank you very much! c# is not my thing. but other languages, you can be sure that I will follow the forum and try to help the staff, I believe this is the idea of the site.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.