function call from Global.asax.cs

S

Steve

I am trying to call a file delete function from inside Session_End in
Global.asax.cs. However, everytime I step into my delete function from
Session_End it jumps to the catch statement and I get the "Object
reference not set to an instance of an object." I don't understand why
it is happening. I would appreciate any help, thanks.

Global.asax.cs
using TheFile = Namespace.TheFile;
private TheFile sessionEnd = new TheFile();

protected void Session_End(Object sender, EventArgs e)
{
sessionEnd.DeleteFile();
}

TheFile.cs
public void DeleteFile()
{
try
{
string filePath = System.Web.HttpContext.Current.Server.MapPath(null);
FileInfo file = new FileInfo(filePath + "/FileName.txt");

if (!Directory.Exists(filePath))
{
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(filePath);
}

if (file.Exists)
file.Delete();
}
catch (Exception e)
{
Console.WriteLine("Error: " + e.Message);
}
}
 
N

Nick Malik

Here's what I believe is happening:

Session End is called after the session times out. When it is called, there
is no HTTP Context. Therefore, the call to
System.Web.HttpContext.Current
returns a null.

You make this call, then you proceed to call the MapPath method on the null
value, which triggers the error.

Store the file name somewhere in a static var so that you can get to it when
the session ends.

--- Nick
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top