简体   繁体   English

FileSystemWatcher - 如何使用它?

[英]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.我有一个关于 FileSystemWatcher 的问题 - 我希望当文本文件 H1.txt 更改里面的值时,我的 ASP.NET webForm 中的标签将刷新。 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 ,我建议使用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回购

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

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