开发者

C# Load items from file and split into array

HI guys i'm trying to 开发者_Go百科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.


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.


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);     
     } 
}


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); 
        } 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜