mercredi 28 octobre 2020

startIndex cannot be larger than length of string.| But i can print the value

I have a problem with the .Substring() method, when a execute a Substring on a string, the compiler, tell me that there is an exeption BUT only in the IF condition, if i try to print the same Substring, magically, the compiler is happy and there's no error. I took set the string with a foreach loop because i'm reading a file

Error

    Unhandled exception. System.ArgumentOutOfRangeException: startIndex cannot be larger than length of string. (Parameter 'startIndex')
   at System.String.Substring(Int32 startIndex, Int32 length)
   at RTFM_Defonseca.Program.readSpedizioni() in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 166
   at RTFM_Defonseca.Program.compatta() in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 181
   at RTFM_Defonseca.Program.Main(String[] args) in C:\Users\Federico\Desktop\Documenti Lavoro Federico\Programmi\RTFM Defonseca\Program.cs:line 43 '

Code

            foreach (var line_collegamento in collegamenti_lines)
            {
                Console.WriteLine(line_collegamento.Substring(3, 20)); //THIS ACTUALLY DOESN'T HAVE PROBLEM
                if (line_collegamento.Substring(3, 20).Equals(codice_collegamento)) //LINE 166, ERROR HERE
                {
                    spedizione.BDA = line_collegamento.Substring(32, 15);
                    lista_spedizioni.Add(spedizione);
                }
            }

Output

Console.WriteLine(line_collegamento.Substring(3, 20))

00310463900043482   
00310463900043482   
00310463900043482
00310463900043482
00310463900043482

//
Console.WriteLine(line_collegamento.Substring(32,15));

00112145001    
00112145002
00112145003
00112145004
00112145005

Aucun commentaire:

Enregistrer un commentaire