簡體   English   中英

FileSystemWatcher - 如何使用它?

[英]FileSystemWatcher - how use it?

大家,早安,

我有一個關於 FileSystemWatcher 的問題 - 我希望當文本文件 H1.txt 更改里面的值時,我的 ASP.NET webForm 中的標簽將刷新。 我做錯了什么?

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

}

我建議使用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
    } 
}

回購

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM