Thursday, July 23, 2009

Write Error message to file ( C#)

This code shows how to write error message to file in C#.net

//Create class for write msg to file
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
///
/// Summary description for clsErrorDisplay
///
public class clsErrorDisplay
{
public void WriteToFile(string ErrStr,string Page)
{
string FilePath = System.Web.HttpContext.Current.Server.MapPath("~/ZipUnzip/log/error.txt");//Add ur path here

if (File.Exists(FilePath))
{
FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
// Write to the file using StreamWriter class
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
m_streamWriter.WriteLine("\n"+Page + "\n");
m_streamWriter.WriteLine(ErrStr + "\n");
m_streamWriter.WriteLine("--------------------------------- \n ");
m_streamWriter.Flush();
m_streamWriter.Dispose();
fs.Close();
}
}
}


Call WriteToFile() from your form...
object.WriteToFile(ex.ToString(), Page.ToString());

No comments: