Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpContext.Current is null while using FileSystemWatcher in C#

I use Forms authentication in my ASP.NET web application and I use FileSystemWatcher in a specific form.

It has two events watcher_Changed and watcher_Created. The events are getting invoked correctly. Once the event gets fired, the HttpContext.Current becomes null.

I don't understand if the session is being cleared by the FileSystemWatcher. Can anyone help me on this? The code is as follows.

void watcher_Created(object sender, FileSystemEventArgs e)
{
    watcher_Event(sender, e);
}

private void watcher_Event(object sender, FileSystemEventArgs e)
{
    try
    {
        if (getUserName() != null)
        {
            //Some Code
        }
    }
}

public string getUserName()
{
    FormsIdentity useridentity = (FormsIdentity)HttpContext.Current.User.Identity;   //Exception is thrown here. ("Object reference not set to instance of an object")
    FormsAuthenticationTicket userticket = useridentity.Ticket;
    string username = userticket.Name;
    return username;
}

Thanks.

like image 639
Vijay Avatar asked Feb 11 '26 05:02

Vijay


1 Answers

The FileSystemWatcher.Changed event is, by its nature, asynchronous. This means that it may be raised after the HTTP request has been serviced, and the session closed. If you want to associate a FileSystemWatcher’s events with the user that caused its creation, you need to maintain this explicitly – for example, by means of a dictionary that maps each FileSystemWatcher to the username.

like image 70
Douglas Avatar answered Feb 14 '26 04:02

Douglas