Click here to Skip to main content
15,843,593 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to read one line from file? When I want to write to file its simply I just create FileStream and FileWriter and write line. But what if I want to read some specific line? I've noticed that FileReader exists too but didn't found nowhere how to use it.
I'am sorry for such noob question I'am learning C# just few days. Thanks for any help.

EDIT: Well so it should look like str = streamReader.ReadLine(); but how can I specify what line I want to read? Can't find how to use ReadLine and msdn explanation is bad :(
Updated 14-Feb-12 11:51am

For line-oriented reading from file/stream, use System.IO.StreamReader:[^].

Share this answer
LosEagle 14-Feb-12 15:24pm    
Thanks :) so it should look like string str = streamReader.ReadLine(); but I can't find how to specify what line to read when I type something into brackets it shows error :-/
Dave Kreskowiak 14-Feb-12 20:53pm    
You can't find the method to do it because it doesn't exist. Since a "line" can be any length, it's impossible to predict where in the file your specified line is going to be.

You have to ReadLine the entire file, counting them along the way, until you get to the specified line you want. If the file is small enough, you can just read the entire file into a String() using ReadAllLines and then you don't need the file anymore. You can just quickly get the line you want from the array of Strings.
Sergey Alexandrovich Kryukov 15-Feb-12 11:00am    
Exactly. One can know the line boundaries only after reading all of them as they have different lengths. Thanks for your help, Dave.
LosEagle 15-Feb-12 9:22am    
Ok thanks :) I think I know what you mean
Sergey Alexandrovich Kryukov 15-Feb-12 11:00am    
You are welcome.
Good luck, call again.
Reading lines from a file is a linear, forward only process. In other words, if you want to read line number N, you read lines 1 through N-1 (and throw them away if you don't need them) and then the next line read will be line N.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900