Click here to Skip to main content
15,899,126 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how to read text file line by line that every timer tick without loop

first line
second line
and the othere line
etc......


C#
int counter = 0;
string line;

// Read the file and display it line by line.
System.IO.StreamReader file =
   new System.IO.StreamReader("c:\\test.txt");
/* i need to read line using timer instead of loop(while)*/
while((line = file.ReadLine()) != null)
{
   Console.WriteLine (line);

}

file.Close();
Posted

1) Create a timer[^] and assign an eventhandler-method to its Elapsed-event (see link).
2) Have the code for opening and closing the file outside of that eventhandler-method. The StreamReader-object should be accessible to the eventhandler-method though (in its scope).
3) In the eventhandler-method do the .ReadLine()
 
Share this answer
 
Something like this could work
int counter = 0;
public static void main()
{
    System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();    
    myTimer.Tick += new EventHandler(ReadFile);   
    myTimer.Interval = 120000;
    myTimer.Start();
}
public void ReadFile()
{
    System.IO.StreamReader file =
       new System.IO.StreamReader("c:\\test.txt");
    /* i need to read line using timer instead of loop(while)*/
    string line = File.ReadLines(FileName).Skip(counter).Take(1).First();
    Console.WriteLine (line);
    counter++;
    file.Close();
}
 
Share this answer
 
v3
Comments
TheSniper105 3-Apr-15 13:01pm    
this will read the entire file every 120000
but i need only to read one line at 120000 milliseconds
then read next line after 120000 milliseconds
how to make that??
Abhinav S 3-Apr-15 13:21pm    
Updated my answer so that file is one line at every tick.
TheSniper105 3-Apr-15 13:27pm    
always read the first line how to move to next line
Abhinav S 3-Apr-15 13:34pm    
Use a counter with Skip (LINQ).
TheSniper105 3-Apr-15 14:05pm    
what is (FileName) and what is the use of
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
why you use ReadLines???

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