Is it possible to get a specific line of txt/csv file using an address?

Asked

Viewed 1,902 times

2

It is possible to access a line from a file txt/csv (example below) by your address directly without having to go through each line using C#?

Exemplo

  • 1

    What do you call each line’s address? Is that number there at the beginning? It is guaranteed to be in ascending order as it appears in this excerpt?

  • Example: I go through the file keeping the key and the line it is on (example 5th line). then there’s some way I can read the file only to get this 5th line? Like it’s an array where I can access a specific position

  • I don’t know if I understand what you want but if I understand correctly you will read the file anyway and you will want to come back in a few points later. First you need to see otherwise it’s better to put everything in memory so you don’t have to access the file again. It might be a better solution. If it is not, you can save this data that you took on the line and still the position of the file where this line starts to be able to access this piece of file directly.

1 answer

8


You can save this data that you picked up on the line along with the position of the file where this line starts to be able to access this part of the file directly at a later time.

Read a specific position of the file in C# use the method Seek() filestream:

using (FileStream fs = new FileStream(@"file.txt", FileMode.Open, FileAccess.Read)) {
    fs.Seek(100, SeekOrigin.Begin); //100 é a posição onde inicia a linha desejada
    byte[] buffer = new byte[200]; //nada garante que a linha não seja maior que 200
    fs.Read(buffer, 0, 200));
}

I put in the Github for future reference.

This ensures random access to any part of the file directly. The Seekorigin.Begin indicates that the position is relative to the beginning of the file, which in the background ends up being the absolute position. It is possible to read from the current position and unlike the end of the file.

Understand by position the byte of the file in sequence.

  • Thank you!! , that’s what I need.

  • I have the slight impression that the position in the FileStream relates to a cursor and not to a line, no?

  • Yeah, and what’s the problem? I didn’t say take the hundredth line, but the hundredth position.

  • I think the first paragraph deals with this "data you picked up on the line along with the position of the file where this line starts to be able to access this section of the file directly at a later time."

  • PEBKAC. Text interpretation failure of my part XD

  • @Renan normal, I always do that too.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.