NerveSinge NerveSinge - 1 month ago 11
C# Question

While loop isn't detecting first line of text file

I have a program that loads text files to populate two separate list boxes in the form. It's supposed to read every line, and add each line to a single listbox. The first line of the text file is being ignored for some reason, and I'm not sure why.

This is what each line of the text file is:


  • cd Armor 1 True+

  • bg Tool 2 False+

  • o Weapon 3 False-

  • xz Consumable 1 True-



I believe my while loop is the issue, but I'm not sure what I'm doing wrong with it. I need the program to loop through more than one line. When I ran the code without using a loop, the first line of the text file was added to the appropriate list box with no issues.

The code below is attached to the load button within my form.

private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openTextFile = new OpenFileDialog();
openTextFile.Filter = "Text Files (*.txt) | *.txt";

string listItemString;
string[] listItem;

if (openTextFile.ShowDialog() == DialogResult.OK)
{
using (StreamReader openStream = new StreamReader(openTextFile.OpenFile()))
{
listItemString = openStream.ReadLine();
listItem = listItemString.Split(' ');

while ((listItemString = openStream.ReadLine()) != null)
{
if (listItemString.EndsWith("+"))
{
listItemString = listItemString.Replace("+", "");
cart.Items.Add(listItemString);
}
else if (listItemString.EndsWith("-"))
{
listItemString = listItemString.Replace("-", "");
delivery.Items.Add(listItemString);
}
}
}
}
}

Answer

You are reading first line before while loop in the line of code listItemString = openStream.ReadLine();. Then you are overridden this value in the first loop iteration when calls while ((listItemString = openStream.ReadLine()) != null) first time.

Just delete 2 lines of code befoer yout loop:

listItemString = openStream.ReadLine();
listItem = listItemString.Split(' ');
Comments