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?
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
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With