当应用程序强行关闭时,如何写关闭原因的日志文件。 [英] How to Write log file with closing reason, when application forcefully closed.
问题描述
大家好,
我创建了Windows应用程序。
需要更新日志文件基于应用程序结束。
我已调用日志文件功能来更新表单结束事件中的原因。
但是,它显示另一个进程使用的错误消息文件。
如果我强行关闭应用程序,日志文件不会保存。
在日志文件中:
使用(StreamWriter sw = File.AppendText(logFile))
任何帮助。
提前致谢。
引用:文件由另一个进程使用。
并猜测它使用该日志文件的应用程序是什么?
嗯,当然,这是你的。
使用不同的设计:必须只有一个类写入日志文件,并调用该类的公共方法,以便在日志文件中添加条目。
您需要从未崩溃的线程运行日志或捕获错误并在try中写入日志。
尝试
{
// 你的崩溃代码
}
catch (例外)
{
// 在此处写下您的日志
}
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 ); // 位于/ bin / debug
sw.WriteLine( 应用程序意外关闭: + System.DateTime.Now.ToString());
sw.Close();
}
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.
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.
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 .
try { //Your crashy code } catch (Exception) { //write your log here }
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(); }
这篇关于当应用程序强行关闭时,如何写关闭原因的日志文件。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!