drunk_coder
drunk_coder

Reputation: 31

Response is not available in this context in event

I have a ASP.NET webpage call page1. In Page_Load(), I created a watcher that watches change of score.txt file:

    var watcher = new FileSystemWatcher(@"D:\");
    watcher.EnableRaisingEvents = true;
    watcher.IncludeSubdirectories = true;
    watcher.Filter = "score.txt";

I want the page to refresh when score.txt file changes, so I add an event like this:

watcher.Changed += (o, a) => 
{
    Response.Redirect(Request.RawUrl);
};

Unfortunately, when I changed the score.txt file manually and save it, the VS2017 throws an exception right at Response.Redirect(Request.RawUrl): System.Web.HttpException: 'Response is not available in this context.'

I try googling but there is still no solution. Could anyone point out what's wrong with my program? Thanks in advance!

Upvotes: 0

Views: 345

Answers (1)

Hans Kesting
Hans Kesting

Reputation: 39255

ASP.Net (and probably all server side frameworks) works with a Request/Response mechanism: a browser sends a Request to the server, the server processes it and sends a Response. After that the connection is gone. There is no way for the server to send a Response when there was no Request (or when that Request has already been handled)

The FileSystemWatcher (that works only on server-side changes - server side code has no access to a client file system) will fire at any time. Usually long after the Response has been sent and that last chance of notification is gone.

So in short, this will never work.

Upvotes: 1

Related Questions