Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
654 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just check the length of the array returned in your if statement

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

The reason you are getting the exception is that the split is returning array of size less than the index you are accessing with. If you are accessing the array element 2 then there must be atleast 3 elements in the array as array index starts with 0


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...