C#写入TXT文件

using System.IO;
using System.Diagnostics;
namespace WebApplication1
{
    public class FileText
    {
        public static string FileAddress = "c:\\error.txt";
        /// <summary>
        /// 记录错误的类名和方法名及错误信息
        /// </summary>
        /// <param name=”className”>出错的类名</param>
        /// <param name=”ex”>错误实例</param>
        public static void Record(Exception ex)
        {
            try
            {
                FileStream fs = null;
                if (!File.Exists(FileAddress))
                {
                    fs = new FileStream(FileAddress, FileMode.Create);
                }
                else
                {
                    fs = new FileStream(FileAddress, 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("调用错误记录的方法:" + transferMethod);
                sw.WriteLine("引发错误的方法:" + ex.TargetSite.ToString());
                sw.WriteLine("错误消息:" + ex.Message.ToString());
                sw.WriteLine("—————————————————————————————–");
                sw.Close();
            }
            catch (IOException ioe)
            {
            }
        }

        public static void WriteString(string Str)
        {
            FileStream fs = null;
            if (!File.Exists(FileAddress))
            {
                fs = new FileStream(FileAddress, FileMode.Create);
            }
            else
            {
                fs = new FileStream(FileAddress, 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("错误消息:" + Str);
            sw.WriteLine("—————————————————————————————–");
            sw.Close();
        }
    }
}

 

你可能感兴趣的:(txt)