开发者

Read content of text file periodically in C# app

I'm playing around with building C# app, really new in C#开发者_JAVA百科. 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!


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.


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
        }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜