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?
There are two options that may help you, depending of whether or not you form incoming data (variable
linesProxy
):proxyAdrs[3]
is the last) parts by adding additional:
between 1st and 3rd values if no value for 2nd is provided. Thus after.Split()
operation (ensure you don't activateRemoveEmptyStrings
option ) yourproxyAdrs[2]
will benull
and your sample will be fine.Otherwise: if
proxyAdrs[2]
is the only part the can be empty following snippet can prevent crashing:Just check the length of the array returned in your if statement
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 atleast3
elements in the array as array index starts with0
Check the length of
proxyAdrs
before you attempt to subscript a potentially non-existent item.You can check the length of array before accessing its element by index.
Change
To
It is that your
i
which might be lower than the2
you are trying to set in as index :)if i >= 2
then you can do all of the follwing:----But again, checking
proxyAdrs.Lenght
would be the best.