Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

c# - Split - Index was outside the bounds of the array

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...