简体   繁体   中英

loading text from file hosts into listbox

i'm making a program to block a website using file hosts,i used streamreader to read it, and i have some problem to load some of its line into a listbox when the form is loaded.
So, here is the example :
file hosts:

127.0.0.1 first.com #onlythis
127.0.0.1 second.com #onlythis
127.0.0.1 third.com #onlythis
127.0.0.1 fourth.com
255.255.255.255 fifth.com
255.255.255.255 sixth.com #onlythis

when program start the listbox would looks like this

first.com
second.com
third.com

so, the program only show the address in the listbox that starts with "127.0.0.1" and ends with "#onlythis". i have done some browsing, and maybe this can be achieved by using StartsWith, Endswith, or maybe Contain. But i dont know how to use it, and i dont know if its can be combined with streamreader. or maybe there are better method to do this?
Thanks.

Assuming they all will be in that specific format:

        string Path = @"C:\test.txt";
        List<string> BlockedHosts = new List<string>();
        using (StreamReader read = new StreamReader(Path))
        {
            while (!read.EndOfStream)
            {
                string[] data = read.ReadLine().Split(' ');
                if (data.Count() >= 3)
                {
                    if (data[0] == "127.0.0.1" && data[2] == "#onlythis")
                    {
                        BlockedHosts.Add(data[1]);
                    }
                }
            }
        }
     //Setting data in listbox
     listBox1.DataSource = BlockedHosts;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM