1. 程式人生 > >C#將錯誤記錄到文字檔案

C#將錯誤記錄到文字檔案

在需要的地方呼叫 

new RecordError().Record(this.Text,ex);

就可以了!

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

    /// <summary>
    /// 作    者:Kogu
    /// 模    塊:記錄錯誤
    /// 建立時間:2008-10-24
    /// 修改時間:2008-10-24
    /// 功能描述:將錯誤記錄到錯誤檔案
    /// </summary>
    public class RecordError
    {
        public RecordError() { }
        /// <summary>
        /// 記錄錯誤的類名和方法名及錯誤資訊
        /// </summary>
        /// <param name=”className”>出錯的類名</param>
        /// <param name=”ex”>錯誤例項</param>
        public void Record(string className,Exception ex)
        {
            try
            {
                FileStream fs = null;
                if (!File.Exists(”error.txt”))
                {
                    fs = new FileStream(”error.txt”, FileMode.Create);
                }
                else
                {
                    fs = new FileStream(”error.txt”, FileMode.Append);
                }
                StackTrace st = new StackTrace(true);
                string transferMethod = st.GetFrame(1).GetMethod().Name.ToString();

                StreamWriter sw = new StreamWriter(fs);
                sw.WriteLine(”—————————————————————————————–”);
                sw.WriteLine(”日    期:” + DateTime.Now.ToString(”G”));
                sw.WriteLine(”類    名:” + className);
                sw.WriteLine(”呼叫錯誤記錄的方法:” + transferMethod);
                sw.WriteLine(”引發錯誤的方法:” + ex.TargetSite.ToString());
                sw.WriteLine(”錯誤訊息:” + ex.Message.ToString());
                sw.Close();
            }
            catch (IOException ioe)
            {
                MessageBox.Show(”錯誤未被記錄!原因:” + ioe.Message.ToString());
            }
        }
    }