Click here to Skip to main content
15,901,284 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi


Index was outside the bounds of the array - Error


C#
 List<string> Messagetype = new List<string>();

using (var reader = new StreamReader(@"C:\Users\Documents\TRWork\Download History\unpack\Estxxx.Acxx.AMER-EARN-2002-2003.1.2016-07-16-0001.Full.1.of.1.txt"))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        //split the line
                        string[] parts = line.Split(new[] { "|" }, StringSplitOptions.None);

                        //get valid text
                        Messagetype.Add(parts[1]);
                        Console.WriteLine(Messagetype.Count()); 
                       
                    }
                }


What I have tried:

I tried Debugging applying breakpoint

I am unable to move to the next line. First line gets read and the string value is stored in the list variable "Messagetype". However after the first loop from while next time when it iterates it does not move to the next line and becomes null
Posted
Updated 21-Jul-16 21:49pm
v2

This has nothing to do with "moving to the next line" - it's too do with the data you read.
C#
string[] parts = line.Split(new[] { "|" }, StringSplitOptions.None);
Messagetype.Add(parts[1]);

When the line you read does not contain any "|" characters then the Split method returns an array containing only one element. So when you try to access the element at index one, it doesn't exist and you get an error.
So start by checking your text file, and see why it has a line which doesn't have any "|" characters.
If that is expected, then check it inside your loop:
C#
string[] parts = line.Split(new[] { "|" }, StringSplitOptions.None);
if (parts.Length > 1)
   {
   Messagetype.Add(parts[1]);
   }
 
Share this answer
 
v2
You should really learn to use the debugger as soon as possible. It is time to see your code executing and ensuring that it does what you expect.

The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]

You will probably see that the error is at
C#
Messagetype.Add(parts[1]);

and that parts[1] do not exist because you split at "|", which is not in line.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900