Split - Index was outside the bounds of the array

2020-02-06 02:46发布

Im using the following code to split up a string and store it:

string[] proxyAdrs = linesProxy[i].Split(':');
string proxyServer = proxyAdrs[0];
int proxyPort = Convert.ToInt32(proxyAdrs[1]);


if(proxyAdrs[2] != null)
{
    item.Username = proxyAdrs[2];
}

if (proxyAdrs[3] != null)
{
    item.Password = proxyAdrs[3];
}

The problem is i am getting

Index was outside the bounds of the array.

When proxyAdrs[2] is not there.

Sometimes proxyAdrs[2] will be there sometimes not.

How can i solve this?

标签: c# split
7条回答
Bombasti
2楼-- · 2020-02-06 03:23

Try this:

        string[] proxyAdrs = linesProxy[i].Split(':');
        string proxyServer = proxyAdrs[0];
        int proxyPort = Convert.ToInt32(proxyAdrs[1]);


        if(proxyAdrs.Length > 2 && proxyAdrs[2] != null)
        {
            item.Username = proxyAdrs[2];
        }

        if (proxyAdrs.Length > 3 && proxyAdrs[3] != null)
        {
            item.Password = proxyAdrs[3];
        }
查看更多
登录 后发表回答