Question

I am trying to read a txt file, from last row to first. It's like this, actually:

randomWord1
randomWord2
randomWord3
...

I'd need to start reading from randomWord3, back to randomWord1, placing every line in a LongListSelector I have already tested out.

I can actually read it from 1 to 3 via this code:

while (!reader.EndOfStream){
    rigaStorico.Add(new Storico(reader.ReadLine()));
}

How can I actually do the exact same, but from 3 to 1? I can't figure that out!

p.s. Of course, the number of rows is NOT KNOWN

Was it helpful?

Solution

There are two simple options using built-in functionality:

Use Reverse (reference):

var rigaStorico = new List<Storico>();

while (!reader.EndOfStream){
    rigaStorico.Add(new Storico(reader.ReadLine()));
}

rigaStorico.Reverse();

Or, you could always Insert (reference) at the beginning of the list the new item:

var rigaStorico = new List<Storico>();

while (!reader.EndOfStream){
    rigaStorico.Insert(0, new Storico(reader.ReadLine()));
}

OTHER TIPS

Something like this ought to work well for you.

public void ReadBackwards(string fileName)
{         
    StreamReader fileStream = new StreamReader(fileName);

    fileStream.BaseStream.Seek(1024, SeekOrigin.End);
    char[] arr = new char[1024];
    while (fileStream.BaseStream.Position > 0)
    {
       arr.Initialize();
       fileStream.BaseStream.Seek(1024, SeekOrigin.Current);
       int bytesRead = fileStream.Read(arr, 0, 1024);
    }
}

//KH.

Maybe a simple solution - as you don't know numer of rows, read them all then add to LLS:

List<Storico> temp = new List<Storico>();
while (!reader.EndOfStream)
{
    temp.Add(new Storico(reader.ReadLine()));
}
for(int n = temp.Count - 1; n >= 0; n--)
    rigaStorico.Add(temp[n]);

EDIT
Althouh this solution works, it needs a temporary List - in fact there are better solutions provided by @WiredPrairie

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top