Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split - Index was outside the bounds of the array

Tags:

c#

split

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?

like image 525
Elvin Avatar asked Nov 27 '12 09:11

Elvin


2 Answers

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

like image 143
Habib Avatar answered Nov 10 '22 18:11

Habib


You can check the length of array before accessing its element by index.

Change

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

To

   if(proxyAdrs.Length > 2 )
   {
            item.Username = proxyAdrs[2];
   }
like image 37
Adil Avatar answered Nov 10 '22 16:11

Adil