Click here to Skip to main content
15,070,680 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How can I read a specific line of a text file (eg. 3rd line of text file) in C#?

Can you please answer me quickly?
:confused:
Posted
Updated 2-Sep-10 1:50am
v3
Comments
Dalek Dave 1-Sep-10 3:29am
   
Minor Edit for Grammar.
CPallini 1-Sep-10 3:35am
   
This is a recurring question, for instance in the C++ forum. There's no magic: you have to read first line 1 and line 2, in order to read line 3 (unless you know in advance the -byte- position of the latter). The hint is in the name: 'file'.
Sandeep Mewara 1-Sep-10 16:51pm
   
Avoid using 'Answer me quickly' next time. People here help when they feel like.

Please don't ask the people doing your job for free to 'answer quickly'.

You can use File.ReadAllLines and then choose the index of the line you want.
   
Comments
demouser743 1-Sep-10 4:18am
   
Reason for my vote of 4
Good one
Hi Jyotshnad,

Ya its possible.But first you can read full text file and then to get particular line value.

C#
// Namespace
using System.IO;  

    Private string ReadTextFile(int nReadLine)
    {
        // For Example nReadLine =3
        int nCount=0;
        string sOutput=sting.Empty;         
         using (StreamReader sr = new StreamReader("C:\\SampleFile.txt"))
            {
                string line;                                
                while ((line = sr.ReadLine()) != null)
                {
                   nCount++;
                   if(nCount==nReadLine) 
                     sOutput=line; 
                }
            }        
        return sOutput;
     }



I hope this code useful to you.

Cheers :)
   
Comments
Kubajzz 2-Sep-10 9:08am
   
Reason for my vote of 2
Your method is not efficient. There is no need to read the whole file if you read it line-by-line... The following is better:

private string ReadLine(int lineNum) {
int count=0;
using (StreamReader sr = new StreamReader("C:\SampleFile.txt")) {
string line;
while ((line = sr.ReadLine()) != null) {
count++;
if (count == lineNum)
return line;
}
}
return null; // It might be appropriate to throw an exception here...
}
Oh sorry

If you are well familiar with strings and all you can do this by using stream reader

Check this one

http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx[^]
   
v3
Comments
Christian Graus 1-Sep-10 3:32am
   
Reason for my vote of 1
How does a string builder have anything to do with reading a file ?

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