繁体   English   中英

在C#app中定期读取文本文件的内容

[英]Read content of text file periodically in C# app

我正在玩C#应用程序,在C#中真的很新。 我想做的是; 让应用程序定期读取文本文件的内容(仅限一个或两个单词)。 文本文件的内容将由其他方式处理,因此没有问题。 我在System.Windows.Forms.Label()的Text上显示内容。 现在,它适用于Click或HandleCreated事件。 但是我想让它自动读取并显示每个内容,比如2分钟。

我看着这个这个,但不确定如何在我的情况下实现它。 有人可以帮忙吗? 谢谢!

创建一个System.Forms.Timer ,将interval设置为2分钟并处理计时器tick事件。

   // 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();

将调用放在方法上以读取文件并将其显示在TimerEventProcessor

在另一个答案中提到的计时器事件中,我希望您每次都要读取该文件,即使某些其他进程当前正在锁定该文件。

但是,如果您不采取预防措施,您将在文件使用时收到异常。 当然,您可以捕获此异常,但是您需要等待几秒钟才能再次尝试。 如果文件仍然被锁定,则可能需要实现一些超时机制。

如果这不是您想要的,另一种支持读取(可能)锁定文件的方法是使用FileShare.ReadWrite参数创建的FileStream对象:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM