Hello :)
Im still learning C# , im developing and application as my project ....
i came across a issue and thought the experts might help me out :)

what i want to do is to read a text file like this :

91.210.46.1:8080
124.193.109.13:80
124.193.109.7:80

and i want to separate the port and the IP ...

example :

IP IS : 91.210.46.1
PORT IS : 8080

IP IS : 124.193.109.13
PORT IS : 80

and so on ... and here comes the huge problem....
i need to store the 2 values to variables when i call a function or something similar to it...

a new IP from the list should be added to the variable on a button click :)
the newly added ip will be used to brows internet by the users :-) from their after ..

hope you got what i meant ...
Thanks alot..

Recommended Answers

All 15 Replies

You can read a file with code that looks like this:

String infile1 = @"c:\ipAddresses.txt";
                StringBuilder currentWords = new StringBuilder();

                StreamReader sr = new StreamReader(infile1);

                try //read the file into lines of data
                {
                    do
                    {
                        currentWords.AppendLine(sr.ReadLine());
                    } while (sr.Peek() != -1);
                }
                catch
                {
                    MessageBox.Show("File [" + infile1 + "] is empty");
                }
                sr.Close(); //close the file
                String final = currentWords.ToString()

infile1 is the directory of your text file. StringBuilder is a special class designed for doing a lot of string concatenations. If you were to concatenate just a normal string many times, it would be very slow.
Once you have your final string, you can use the Split method to split the string into two strings around the colon.

what i want to do is to read a text file like this :

91.210.46.1:8080

and i want to separate the port and the IP ...
example :

IP IS : 91.210.46.1
PORT IS : 8080

i need to store the 2 values to variables when i call a function or something similar to it...

In general, you can do this kind of thing using regular expressions with grouping constructs.

This is a simple case, though, and you don't have to bust out a regex. Here's an example of how you might parse each line.

You can read a file with code that looks like this:

String infile1 = @"c:\ipAddresses.txt";
                StringBuilder currentWords = new StringBuilder();

                StreamReader sr = new StreamReader(infile1);

                try //read the file into lines of data
                {
                    do
                    {
                        currentWords.AppendLine(sr.ReadLine());
                    } while (sr.Peek() != -1);
                }
                catch
                {
                    MessageBox.Show("File [" + infile1 + "] is empty");
                }
                sr.Close(); //close the file
                String final = currentWords.ToString()

infile1 is the directory of your text file. StringBuilder is a special class designed for doing a lot of string concatenations. If you were to concatenate just a normal string many times, it would be very slow.
Once you have your final string, you can use the Split method to split the string into two strings around the colon.

I don't think StringBuilder is appropriate here, as we need to treat each line as a separate IP endpoint... all this does is cram the contents of the file into a string without separating them. A List<string> would be much more useful. But you're going to want to build IPEndpoints anyway, so why not convert inline? Also, StreamReader.ReadLine will actually tell you when the file's done; no need to peek.

Improved code:

List<IPEndPoint> endpoints = new List<IPEndPoint>();
StreamReader reader = new StreamReader("filename.txt");

string line;
while((line = reader.ReadLine()) != null)
{
    string[] parts = line.Split(':');
    
    if(parts.Length == 2)
    {
        // We have two parts, which are hopefully an IP
        // address and a port number. Let's see...
        
        IPAddress address;
        int port;
        
        if(IPAddress.TryParse(parts[0], out address) &&
           Int32.TryParse(parts[1], out port))
        {
            // If both 'TryParse' calls succeeded, it's
            // a real endpoint, so add it to the list.
            
            endpoints.Add(new IPEndPoint(address, port));
        }
    }
}

// Now you have all of the valid IP endpoints from the file
// loaded into 'endpoints', ready to use to create connections.

I don't think StringBuilder is appropriate here, as we need to treat each line as a separate IP endpoint... all this does is cram the contents of the file into a string without separating them. A List<string> would be much more useful. But you're going to want to build IPEndpoints anyway, so why not convert inline? Also, StreamReader.ReadLine will actually tell you when the file's done; no need to peek.

Improved code:

List<IPEndPoint> endpoints = new List<IPEndPoint>();
StreamReader reader = new StreamReader("filename.txt");

string line;
while((line = reader.ReadLine()) != null)
{
    string[] parts = line.Split(':');
    
    if(parts.Length == 2)
    {
        // We have two parts, which are hopefully an IP
        // address and a port number. Let's see...
        
        IPAddress address;
        int port;
        
        if(IPAddress.TryParse(parts[0], out address) &&
           Int32.TryParse(parts[1], out port))
        {
            // If both 'TryParse' calls succeeded, it's
            // a real endpoint, so add it to the list.
            
            endpoints.Add(new IPEndPoint(address, port));
        }
    }
}

// Now you have all of the valid IP endpoints from the file
// loaded into 'endpoints', ready to use to create connections.

Yup your solution is better. The bit of code I posted is something I just knew I already had.

@ gusano79 - Thank you very much ,, this really helps me alot... thank you for finding me the best solution :)

@ kimbokasteniv - Thank you too ;-) i really appreciate it

So, does your code work like you want to?

one more question :-)
i see that the IP is stored in 'endpoints'

does all the IP list is stored here is it stored 1 by 1 ..
i need to load a new IP and port to vars on a button click,,
can you help me to make this a function and use it on a button or a instance to update the varable with latest ip and port ?

thank you :-)

So, does your code work like you want to?[/QUOTE

It solved a big problem .. but i still have doubts :S i posted a reply with my question...
thanks

There is maybe a bit different approach, to use a generic list, which will save all the IPs and their gates.

List<MyIP> list;
        private void ReadFile_WithIP()
        {
            list = new List<MyIP>();
            using (StreamReader sr = new StreamReader(@"C:\YourFolder\YourFileName"))
            {
                string line;
                while ((line = sr.ReadLine()) != null)
                {
                    string[] array = line.Split(':');
                    MyIP _ip = new MyIP();
                    _ip.IPport = array[0];
                    _ip.Gate = array[1];
                    list.Add(_ip);
                }
            }
        }

        internal class MyIP
        {
            public string IPport { get; set; }
            public string Gate { get; set; }
        }

To get all our your can do it:

foreach (MyIP _ip in list)
            {
                string _ipPort = _ip.IPport;
                string _gate = _ip.Gate;
            }

To answer on your last question, you can easily do if you will use my code with a genric list:

private void button1_Click(object sender, EventArgs e)
        {
            //get 1. ip from the list (if there are many):
            textBox1.Text = list.Select(s => s.IPport).First();
            textBox2.Text = list.Select(s => s.Gate).First();
        }

i see that the IP is stored in 'endpoints' does all the IP list is stored here is it stored 1 by 1 ..

If I understand you correctly, yes, every single IP endpoint in the file will be added to the list.

i need to load a new IP and port to vars on a button click,,
can you help me to make this a function and use it on a button or a instance to update the varable with latest ip and port ?

I'm not sure what exactly you want to do here... just take the last (latest?) line of the file and assign it somewhere? The last entry is in endpoints[endpoints.Length - 1] . As far as doing something from a button, if you make endpoints a member of the form, you can access it directly from the handler for your button's click event.

_ip.IPport = array[0];
_ip.Gate = array[1];

This looks backward; the port should come after the colon, not before.

internal class MyIP
{
    public string IPport { get; set; }
    public string Gate { get; set; }
}

Storing the endpoint information in strings is fine if all you want to do is display the values, but if you want to actually create a connection, you'll still have to create an IPEndPoint anyway. Also, there's no validation here, so something like "XXX#$%^&:snarkus" would get passed along as a valid IP address/port pair, which it isn't.

Picking at names... "IPport" can just be "Port" since you already have "IP" in the class name; no need to be redundant. "Gate" doesn't make any sense here, it should be "Address"; this is more or less universal terminology.

If I understand you correctly, yes, every single IP endpoint in the file will be added to the list.

I'm not sure what exactly you want to do here... just take the last (latest?) line of the file and assign it somewhere? The last entry is in endpoints[endpoints.Length - 1] . As far as doing something from a button, if you make endpoints a member of the form, you can access it directly from the handler for your button's click event.

Thanks alot of helping me out,, let me tell you what i need exactly ..
im going to load a text file with SET OF IP's and ports in it ... multiple values ..
then after that ,, i need to load a SINGLE IP with PORT To a text-Box on a button click,,

a sample instance might be like when i click on the button it should load the 1st "IP AND PORT" in the list to a text box then and again when i click on that button it should load the 2nd "IP AND PORT" to the text box ... then and again if the user clicks on that button the 3rd "IP AND PORT" should be loaded into text box ;-)

Simple as that ;-)

hope you got what i exactly needed to do ;)
Thank you !

To answer on your last question, you can easily do if you will use my code with a genric list:

private void button1_Click(object sender, EventArgs e)
        {
            //get 1. ip from the list (if there are many):
            textBox1.Text = list.Select(s => s.IPport).First();
            textBox2.Text = list.Select(s => s.Gate).First();
        }

Thank you very much ;-)
i have a lil doubt though ...

well i need to update the textBox1 and textBox2 with the 2nd "IP AND PORT" in the list when i click on the same button again and when i click it again for the 3rd time the same textboxes should load the 3rd "IP AND PORT"

it needs to load the "IP AND PORT" line by line when i click on the same button..\could you kindly help me to create a auto increment function for this or is their a better solution ?

Thank you !
Thank you very much

declare an int count in you class and update it when you click the button and put the IP and PORT on count location in textboxes Hopefully it will help you

int count=0;

   private void button2_Click(object sender, EventArgs e)
            {
//if String IP --> holding ur ip's string PORT-->holding ur ports
textBox1.Text=IP[count];
textBox2.Text=PORT[count];
count++;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.