简体   繁体   中英

How to read from a text file that is constantly updating and write to a TextBlock in Visual Studio? [on hold]

I am doing a project that needs to report the distances from 5 ultrasonic sensors that update the distance every 200ms. I want to have these distances updated in a GUI. I currently have the distances being written to a text file. How would I read from that text file and get all five distances to write to the TextBlocks and get updated every 200ms?

Hello and welcome @mjbll123,

You could force the program to "wait" until the file is available with a small method:

public string WaitForFile(string file)
{
    try
    {
        //using variable to make sure the return doesn't get executed
        string tmp = File.ReadAllText(file);
        return tmp;
    }
    catch(Exception)
    {
        return WaitForFile(file);
    }
}

What this actually does, is trying to access the file and read it at once. If it fails ( IOException ), then it tries again (in the catch block).

You can use System.IO.FileSystemWatcher class. This will raise an event when the file is changed. You can read the file in the event and update the GUI. A sample method would be like:

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = yourFilePath;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

In the EventHandler make sure you read the file using below, to ensure reading event if it is open for writing in other program.

private void OnChanged(object source, FileSystemEventArgs e)
{
  using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(fs, Encoding.Default)) {
    // read the stream
    var fileText = sr.ReadToEnd();
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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