0

HI guys i'm trying to load the contents of my file "item.ids" which currently holds this:

1:Stone
2:Grass
3:Dirt

I want to read each line the the file and split it at the ":". I am using the following code:

    foreach(String line in File.ReadAllLines("item.ids")) {
        items = line.Split(':');
    }

    foreach (String part in items)
    {
        addToList(specs, part);
    }



}


public void addToArray(Array array, int index, String s)
{
    try
    {

        array.SetValue(s, index);
    }
    catch (Exception ex)
    {
        addToList(specs, ex.ToString());
    }
}

public void addToList(ListBox listbox, String s)
{
    listbox.Items.Add(s);
}

This works but it only does the last line so it will output it like so:

3
dirt

If you could help me along with my code it would be very helpful.

1
  • Where are you calling addtoarray? Agar exactly are you wanting to do with your values? Commented Sep 16, 2011 at 2:19

3 Answers 3

4

You need to fill the list after every read.

foreach(String line in File.ReadAllLines("item.ids")) 
{
    items = line.Split(':');

    foreach (String part in items)
    {
        addToList(specs, part);
    }
}

... otherwise you're only ever adding the last item by default.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes haha, That's why. Thanks :)
1

In the 1st loop you set the item field each time you iterate so when you exit the loop it will be set to the last value. You probably want to change to something like this:

foreach(String line in File.ReadAllLines("item.ids")) 
{         
     foreach (String part in line.Split(':'))
     {         
          addToList(specs, part);     
     } 
}

Comments

0

You've closed your loop to early so items will only contain the last iteration

change your code to:

    foreach(String line in File.ReadAllLines("item.ids")) 
    { 
        items = line.Split(':'); 

        foreach (String part in items) 
        { 
            addToList(specs, part); 
        } 
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.