LoginSignup
7
8

More than 5 years have passed since last update.

Rxを使ってファイルが変更されたタイミングでWPF画面に反映する

Last updated at Posted at 2014-01-27
public partial class MainWindow : Window
{
    private FileSystemWatcher watcher;

    private IDisposable obs;

    public MainWindow()
    {
        InitializeComponent();

        var f = new FileInfo(@"C:\temp\Sample1.txt");

        this.watcher = new FileSystemWatcher();
        this.watcher.Path = f.Directory.FullName;
        this.watcher.Filter = f.Name;
        this.watcher.NotifyFilter = NotifyFilters.LastWrite;
        var o = Observable.FromEvent<FileSystemEventHandler, FileSystemEventArgs>(
            a => (obj, e) => a(e),
            h => this.watcher.Changed += h,
            h => this.watcher.Changed -= h,
            DispatcherScheduler.Current);
        this.obs = o.ObserveOnDispatcher()
            .Select(x => GetContents(f))
            .Subscribe(x => {
                this.mainText.Text = x;
            });

        this.watcher.EnableRaisingEvents = true;
    }

    private string GetContents(FileInfo f)
    {
        using (var st = f.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        using (var r = new StreamReader(st)) {
            return r.ReadToEnd();
        }
    }
}

DispatcherScheduler.Current + ObserveOnDispatcher() メソッドがポイントかしら。

7
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
8