Click here to Skip to main content
15,888,527 members
Please Sign up or sign in to vote.
1.00/5 (5 votes)
See more:
i do not want to read the entire file. i just want my program to read first five words from the file.

What I have tried:

i used readalllines and readalltext.. but it read the whole file
Posted
Updated 7-Jan-18 22:55pm
Comments
Richard MacCutchan 8-Jan-18 4:43am    
Then don't use readalllines/readalltext.

TextReader is nice:[^]

example from link:
using (TextReader reader = File.OpenText(@"C:\perl.txt"))
{
    string line = reader.ReadLine();
    Console.WriteLine(line);
}
 
Share this answer
 
So read it char-by-char and stop after 5 words...
StreamReader.Read Method (Char[], Int32, Int32) (System.IO)[^]
 
Share this answer
 
Repeadly use Readline, until you get the required words. See, for instance: How to: Read a Text File One Line at a Time (Visual C#) | Microsoft Docs[^].
 
Share this answer
 
try

string filePath = @"D:\Tools\abc.txt";
        string first5Words = "";
        int maxWords = 5, count = 0;
        using (StreamReader reader = new StreamReader(filePath))
        {
            while (reader.Peek() >= 0)
            {
               char c = (char)reader.Read();
               char[] ChartoFindNewWord = { ' ', '\t', '\n', '\r' };
                if(ChartoFindNewWord.Contains(c))
                {
                    count++;
                    if(count >= maxWords)
                    break;
                }
                first5Words += c; 
            }
            
        }

        string output = first5Words;
 
Share this answer
 
v2
Comments
c#Beginnerrrr 8-Jan-18 5:03am    
Will have a try..Thank you:)
Karthik_Mahalingam 8-Jan-18 5:07am    
ok, let know if you face any issue
c#Beginnerrrr 8-Jan-18 5:38am    
ya its working fine....i have one more query.. can you please help me with this?
Karthik_Mahalingam 8-Jan-18 5:40am    
If the query is related to this thread then proceed, else post a new question.
c#Beginnerrrr 8-Jan-18 5:48am    
okay

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