Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# add textfile to 2 dimensional array

Tags:

arrays

c#

I'm trying to read a text file, which contains proxys into a 2 dimensional array.

The text file looks like the following:

00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80
00.00.00.00:80

How could I seperate the ip from the port?`

So my array would look like the following:

[00.00.00.00][80]

Current code:

public void readProxyList(string FileName)
{
    using (StreamReader sr = new StreamReader(FileName, Encoding.Default))
    {
        string text = sr.ReadToEnd();
        string[] lines = text.Split('\r');

        foreach (string s in lines)
        {

        }
    }
}
like image 966
dnxc Avatar asked Apr 17 '26 04:04

dnxc


1 Answers

If you are not expecting the file to be too large you could use File.ReadAllLines to read in each line. Then to split, just use String.Split with ':' as your token.

Example:

var lines = File.ReadAllLines(FileName));
var array = new string[lines.Length,2];
for(int i=0; i < lines.Length; i++)
{
    var temp = lines[i].Split(':');
    array[i,0] = temp[0];
    array[i,1] = temp[1];
}

Edit

If you expect that the file may be large, instead of using ReadAllLines you can use File.ReadLines. This method returns an IEnumerable<string> and will not read the whole file at once. In this case, I would probably opt away from the 2d array and make a simple class (call it IpAndPort or something like that) and create a list of those.

Example:

public sealed class IpAndPort
{
    public string Ip { get; private set; }
    public string Port { get; private set; }
    public IpAndPort (string ip, string port)
    {
        Ip = ip;
        Port = port;
    }
}

var list = new List<IpAndPort>();
foreach(var line in File.ReadLines(FileName))
{
    var temp = line.Split(':');
    list.Add(new IpAndPort(temp[0], temp[1]);
}
like image 163
pstrjds Avatar answered Apr 18 '26 20:04

pstrjds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!