Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi All,

I have created Windows application.

Need to update the log file based on application closing.

I have called Log file function to update the reason in Form Closing event.

But, it shows an error message file is used by another process.

If i forcefully shut down the application, log file is not saving.

In Log file:
using (StreamWriter sw = File.AppendText(logFile))

Any help on this.

Thanks in advance.
Posted
Updated 4-Aug-14 0:55am
v2
Comments
Prasad Avunoori 4-Aug-14 7:32am    
I think Threading concept could help you.

Quote:
file is used by another process.
And guess which application it is which uses that log file?
Well, of course, it's yours.
Use adifferent design: there must be only one class which writes to the log file, and call a public method of that class for adding an entry to the log file.
 
Share this answer
 
You need to run the log from a thread that didn't crash or capture the error and write to the log in a try .

C#
try
{
    //Your crashy code
}
catch (Exception)
{
    //write your log here
}
 
Share this answer
 
C#
private void ClosingForm_FormClosing_1(object sender, FormClosingEventArgs e)
       {

           Thread thread1 = new Thread(new ThreadStart(log));
           thread1.Start();


       }

       void log()
       {
           string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
           string folderpath = System.IO.Path.GetDirectoryName(path);
           string logFilePath = folderpath + @"\log.txt";

           if (!System.IO.File.Exists(logFilePath))
           {
               System.IO.File.Create(logFilePath);
           }

           StreamWriter sw = new StreamWriter(logFilePath,true); //located in /bin/debug
           sw.WriteLine("Application closed accidentally at : "+System.DateTime.Now.ToString());
           sw.Close();

       }
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900