0

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

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Shaked Dahan
  • 402
  • 5
  • 22
  • 5
    First you should always include the exception type, message and stacktrace that was thrown. Secondly, applications run under an application pool that has an identity on the system/domain. This use most likely does not have access to write a file to the file system. – Erik Philips May 06 '15 at 19:14
  • have you tried creating a custom class and then adding that code to see if it works.. if you are redirecting to an error page have you also considered putting the code in that page in it's page_load method or creating a static method in that page..? did you use the debugger..? does it even hit the `Application_Error` method.. if so what line is causing the error.. this it what the debugger is there for – MethodMan May 06 '15 at 19:15
  • 2
    "It doesn't work" isn't really a helpful description. When you debug this, where does it fail? Does this code get invoked at all? Is there any error when it executes? Is the file created at all? Why not simplify this code to something like `File.AppendAllText()`? – David May 06 '15 at 19:15
  • "So do you have any idea what is wrong with my code?" - No, do you ? – Dimitar Tsonev May 06 '15 at 19:16
  • Sounds crazy but close your visual studio project. Right click on your solution or Visual Studio and click "Run As Administrator". I have had this happen to me when I was developing...I don't know if you've heard of elmah but check this link out --> https://code.google.com/p/elmah/ I've used this in many projects and love it! – waltmagic May 06 '15 at 19:17
  • @waltmagic thanks... stupid of me to not run it as administrator – Shaked Dahan May 06 '15 at 19:19
  • also add code to `Flush` the data before closing.. – MethodMan May 06 '15 at 19:20
  • 1
    In an ASP.NET application, you may not have access to write a text file. Have you considered just doing nothing and looking in the Event Log? Or implementing [ASP.NET Health Monitoring](https://msdn.microsoft.com/en-us/library/bb398933.aspx)? It looks complicated, but simply adding `` to web.config in the `` section is usually enough. – John Saunders May 06 '15 at 19:20
  • Also, your `TextWriter` should be in a `using` block. – John Saunders May 06 '15 at 19:21
  • 1
    @Shaked Dahan No problem, glad I could help. Check out elmah, I really think you would like it. – waltmagic May 06 '15 at 19:22
  • @waltmagic If your app need administrator rights to run, then you're probably doing something wrong... – Etienne Maheu May 06 '15 at 20:17
  • @Etienne Maheu none of the apps I develop need admin rights and whatever rights they would need would be set when the application was deployed...when developing in VS however I have needed to run Visual Studio as administrator occasionally – waltmagic May 06 '15 at 20:32

3 Answers3

1

One problem with your code is that you don't have a using block for your File.Create call. The problem is that this method creates a file and returns a stream. The stream will most likely still be locking the file when you try to write to it.

To resolve this, you can use an empty using block that will close and dispose of the stream, like so:

if (!File.Exists(path))
{
    using (File.Create(path)) { }
}

A related problem that may not always rear it's head is that you are not disposing of your TextWriter. You should also wrap the code that uses that in a using block, to ensure it's taken care of (and you can remove the call to .Close since that will happen automatically):

using (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(@"}");
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43
0

Your problem could be due to the use of Server.MapPath.

Try changing:

string path = Server.MapPath("Error.txt");

To something like:

string path = String.Format("{0}\\{1}", HttpRuntime.AppDomainAppPath, "Error.txt");
b_stil
  • 2,475
  • 2
  • 12
  • 5
-2

I just had to run visual studio as administrator, dont waste time trying to add more answers\comments, this problem is solved

Shaked Dahan
  • 402
  • 5
  • 22
  • It may be solved to you, but not to others in the future that may have the same problem. If you found the solution yourself please post it as an answer and accept your own answer. – Carlos Muñoz May 06 '15 at 19:57