简体   繁体   中英

FileSystemWatcher - how use it?

Good morning everyone,

I have a question about FileSystemWatcher - I want when the textfile H1.txt change value inside, the label in my ASP.NET webForm will refresh. What I do wrong?

 TextReader tr = new StreamReader(@"C:\Help\H1.txt");


    Label1.Text = tr.ReadLine() + " °C";
    Label1.Text  += tr.ReadToEnd();

    tr.Close();

    FileSystemWatcher fwatcher = new FileSystemWatcher();

    

    fwatcher.Path = Path.GetDirectoryName(@"C:\Help\H1.txt"); 
    fwatcher.Filter = Path.GetFileName(@"C:\Help\H1.txt");

    //types of events to watch 
    fwatcher.NotifyFilter = NotifyFilters.LastWrite;
    fwatcher.EnableRaisingEvents = true;


   fwatcher.Changed += Changed;




}

public void Changed(Object sender, FileSystemEventArgs e)
{
    TextReader tr = new StreamReader(@"C:\Help\H1.txt");
    Label1.Text = tr.ReadLine() + " °C";
    Label1.Text += tr.ReadToEnd();

    tr.Close();

}

I suggest using SignalR ,

protected void OnChanged(object sender, FileSystemEventArgs e)
{
    if (e.ChangeType != WatcherChangeTypes.Changed)
    {
        return;
    };
    try
    {
        using (TextReader tr = new StreamReader(e.FullPath))
        {
            var text = tr.ReadLine() + " °C";
            var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
            context.Clients.All.broadcastMessage("server", text);
        }
    }
    catch
    {
        // ignore any error
    } 
}

Repo

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