Convert.ToInt32 takes a string and converts it to an integer - but if the string contains any characters which are not digits, then it will throw an exception.
You need to use the debugger to look at exactly what you are passing to Convert.ToInt32 - so break it out a bit:
string bitStrengthString = PublicKey.Substring(0, PublicKey.IndexOf("</BitStrength>") + 14);
string part1 = bitStrengthString.Replace("<BitStrength>", "");
string part2 = part1.Replace("</BitStrength>", "");
int KeySize = Convert.ToInt32(part2);
Now put a breakpoint on the final line, and look at what is in
part1
and
part2
.
Until you know that, you have no idea what you need to do to fix this - and we can't do that for you!