Reading a text file

I am trying to reach a situation where I load a file into a program. I can use streamreader for this. Each entry will be 7 lines long. Therefore lines 1,8,15,22, etc. Will have the same meaning. As well as 2,9,16,23 etc. Etc.

What is the best way to achieve this? So when I load the entries into the listview, it recognizes what I just said. Thanks to

+2


a source to share


3 answers


When you say that lines 1, 8, 15, etc. will have the same value, do you really mean that they have the same value type? Otherwise, why read more than the first 7 lines?

I think something like below might work (didn't test the code).



string data;
using(System.IO.StreamReader reader = new System.IO.StreamReader("filepath"))
{
    data = reader.ReadToEnd();
}

string[] lines = data.Split(Environment.NewLine);

for(int index = 0; index < lines.Length; index += 7)
{
    ListViewItem item = new ListViewItem();
    for(int innerIndex = 0; innerIndex < 7; innerIndex++)
    {
        item.SubItems.Add(lines[index + innerIndex]);
    }

    listView1.Items.Add(item);
}

      

+3


a source


It looks like you need to create a class that will represent each entry (one property for each of the 7 rows).

Open the stream reader.

Do, start loop while there are still lines to read.



For each iteration of your loop, read 7 lines into seven variables, then create a new instance of your class and set each property to the value contained in the corresponding variable.

Add this class to your collection (for example, List <MyClass>,).

Your ListView should use the collection of objects that you created. Now you can select a property to act as a display value.

+1


a source


create array [num_lines / 7] x [7] 2D

for (int i=0;i<num_lines/7;i++)
    for (int t=0;t<7;t++)
        my2darray[i][t] = orig_array[i*7+t];

      

If I understand your question correctly, which will order your data in the desired way

0


a source







All Articles