Reputation: 11
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();
}
Upvotes: 0
Views: 85
Reputation: 592
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
}
}
Upvotes: 1