I'm trying to write some info to a text file when there is an error in the application. I added this code to the Application_Error
method in global.asax
but it still dont work:
void Application_Error(object sender, EventArgs e)
{
string path = Server.MapPath("Error.txt");
Exception ex = Server.GetLastError();
if (!File.Exists(path))
{
File.Create(path);
}
if (File.Exists(path))
{
TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("{0} : An Error Has Occurred, Error Description",DateTime.Now.ToString());
tw.WriteLine(@"{");
tw.WriteLine("Error Message: {0}", ex.Message);
tw.WriteLine("Source: {0}", ex.Source);
if (ex.StackTrace != null) tw.WriteLine("StackTrace: {0}", ex.StackTrace);
tw.WriteLine(@"}");
tw.Close();
}
}
If it matters, i'm also redirecting to an error page when there is an error, here is the web.config file:
<customErrors mode="On" defaultRedirect="ASPX/Error.aspx" redirectMode="ResponseRedirect">
<error statusCode="404" redirect="ASPX/Error404.aspx"/>
</customErrors>
So do you have any idea what is wrong with my code? how can I make it write the text into the file?
Edit: I just needed to run vs as administrator, the probelm is solved