Hi All,
I am very new to C# language.I am working on an application in which I have to create an event log file in which I have to capture the entries from a text box and put them in the log file.What should be the code?
I am very new to C# language.I am working on an application in which I have to create an event log file in which I have to capture the entries from a text box and put them in the log file.What should be the code?
Scott LyslePosted May 28, 2008, 3:31 PM
Here is a simple class you can use to write error messages to a text file located in the path of the application in an error log file:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace Exceptions
{
///
/// Write Error Message to a text
/// file
///
public class ErrorLogger
{
// default constructor
public ErrorLogger()
{
}
// overloaded constructor
public ErrorLogger(string msg, string stkTrace,
string title)
{
WriteToErrorLog(msg, stkTrace, title);
}
///
/// Write to Error Log (Text File)
///
/// The message text
/// to write
/// The stack trace
/// for the exception
/// The name of the error
public void WriteToErrorLog(string msg,
string stkTrace, string title)
{
// check and make the directory if necessary;
// this is set to look in the application
// folder, you may wish to place the error
// log in another location depending upon the
// the user's role and write access to different
// areas of the file system
if(!System.IO.Directory.Exists(
Application.StartupPath + "\\Errors\\"))
{
System.IO.Directory.CreateDirectory(
Application.StartupPath + "\\Errors\\");
}
string DateAppendage = DateTime.Now.Month.ToString() + "_" +
DateTime.Now.Day.ToString() + "_" +
DateTime.Now.Year.ToString();
// check the file, create it if necessary - do not
// write the message in this pass,
FileStream fs = new FileStream(Application.StartupPath +
"\\Errors\\errlog_" + DateAppendage + ".txt",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter s = new StreamWriter(fs);
s.Close();
fs.Close();
fs.Dispose();
// re-open the log file and log the message
FileStream fs1 = new FileStream(Application.StartupPath +
"\\Errors\\errlog_" + DateAppendage + ".txt",
FileMode.Append, FileAccess.Write);
StreamWriter s1 = new StreamWriter(fs1);
s1.Write("Title: " + title + Environment.NewLine);
s1.Write("Message: " + msg + Environment.NewLine);
s1.Write("StackTrace: " + stkTrace + Environment.NewLine);
s1.Write("Date/Time: " + DateTime.Now.ToString()
+ Environment.NewLine);
s1.Write("==============================" +
Environment.NewLine);
s1.Close();
fs1.Close();
fs1.Dispose();
}
}
}