tags:

views:

46

answers:

2

I'm playing around with building C# app, really new in C#. What I'm trying to do is; make the app periodically read the content of a text file (in one or two words only). The content of the text file will be handled by other mean, so no issue on that. I'm displaying the content on the Text of System.Windows.Forms.Label(). Right now, it works on Click or HandleCreated event. But I want it to automatically read and display the content in every, say, 2 minutes.

I looked at this and this but not really sure how to implement it on my case. Anyone can help? Thanks!

+3  A: 

Create a System.Forms.Timer, set interval to 2 minutes and handle the timer tick event.

   // Declare at form class scope
   System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

   // ...

   myTimer.Tick += new EventHandler(TimerEventProcessor);

   // Sets the timer interval to 120 seconds (2 minutes).
   myTimer.Interval = 120000;
   myTimer.Start();

Place the calls to the methods to read the file and display it in TimerEventProcessor.

Mitch Wheat
That really helps. Thanks a lot !
flisterz
+1  A: 

In the timer event mentioned in another answer, I expect you will want to read the file every time, even if some other process is currently locking the file.

But if you don't take precautions you will receive an exception whenever the file is in use. You can catch this exception of course, but you will then need to simply wait for a few seconds before trying again. If the file is still locked you may need to implement some timeout mechanism.

If this is not what you want, another approach that supports reading of (possibly) locked files is to use a FileStream object created with the FileShare.ReadWrite parameter:

        // Inside your timer event.
        using (System.IO.FileStream fs = new System.IO.FileStream("yourfile.log", 
               System.IO.FileMode.Open, System.IO.FileAccess.Read, 
               System.IO.FileShare.ReadWrite))
        {
            // use fs to read from file as required
        }
Ash
This is going to be useful. Thanks! will try to implement it.
flisterz