Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / system

“csc.exe – Application Error” when Shutting Windows with a Running .NET Application

0.00/5 (No votes)
7 May 2023CPOL1 min read 5.6K  
Fix for “csc.exe – Application Error”
In this post, you will learn how to fix csc.exe – Application Error when shutting Windows with a running .NET app.

Recently, a friend reported to me that my application written in .NET prevents his computer from shutting down. If the application is running when Windows tries to shut down, the following error message appears and Windows cannot shut down:

csc.exe – Application Error

The application failed to initialize properly (0xc0000142). 
Click on OK to terminate the application.

Some investigation reveals that the issue has to do with the .NET class XmlSerializer. My application stores user data into an XML file, which gets saved when the application is closed. In particular, the following code seems to cause the problem:

VB.NET
Dim serializer As New XmlSerializer(ConfigObj.GetType())
Dim writer As New StreamWriter(datafile)
serializer.Serialize(writer, ConfigObj)
writer.Close()

The error occurs as soon as XmlSerializer.Serialize() is called. A file system monitor tool such as Process Monitor shows me that csc.exe is creating temporary files in C:WindowsTemp, which is perhaps interrupted by the shutdown process, causing the above problem. I am not even sure why csc.exe (the Microsoft C# compiler) gets called even though I am using VB.NET!

Not sure how to fix the problem, I have to avoid calling XmlSerializer when Windows is shutting down by using:

VB.NET
Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
…

If e.CloseReason <> CloseReason.WindowsShutDown 

   Dim serializer As New XmlSerializer(ConfigObj.GetType())
   Dim writer As New StreamWriter(datafile)
   serializer.Serialize(writer, ConfigObj)
   writer.Close()

End IfEnd Sub

This way, user data may be lost, but at least my application does not prevent the system from shutting down. I have to find another way to save user data more frequently…

Reference

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)