string path = @"..\..\ErrorMesage";
if(!System.IO.Directory.Exists(path))
{
    System.IO.Directory.CreateDirectory(path);
    using(StreamWriter sw = File.CreateText(path+@"\errorMessage.txt"))
    {
        sw.WriteLine("【");
        sw.WriteLine("错误时间:"+dt);
        sw.WriteLine("错误信息:"+errorMessage);
        sw.WriteLine("错误位置:"+StackTrace);
        sw.WriteLine("】");
        sw.WriteLine("\r\n");
    }
}
else
{
    using(StreamWriter sw = File.CreateText(path+@"\errorMessage.txt"))
    {
        sw.WriteLine("【");
        sw.WriteLine("错误发生时间:"+dt);
        sw.WriteLine("错误信息:"+errorMessage);
        sw.WriteLine("错误发生位置:"+StackTrace);
        sw.WriteLine("】");
        sw.WriteLine("\n");
     }
}
这样每次有错误信息的写入的时候,都会覆盖上一次的信息,如何追加在后面而不是覆盖呢?

解决方案 »

  1.   

    StreamWriter sw = File.CreateText(path+@"\errorMessage.txt"))改为
    StreamWriter sw = new StreamWriter(path+@"\errorMessage.txt",true)
      

  2.   

    使用重载的构造函数,指定追加方式为true
      

  3.   

    System.IO.StreamWriter sw = new System.IO.StreamWriter(path+@"\errorMessage.txt",true);
      

  4.   

    using(StreamWriter sw = File.AppendText(path+@"\errorMessage.txt"))
        {
            sw.WriteLine("【");
            sw.WriteLine("错误发生时间:"+dt);
            sw.WriteLine("错误信息:"+errorMessage);
            sw.WriteLine("错误发生位置:"+StackTrace);
            sw.WriteLine("】");
            sw.WriteLine("\n");
         }
      

  5.   

    StreamWriter sw = File.AppendText(LogFile);
                    try
                    {
                        sw.WriteLine(string.Format("[{0}] [{1}] [Visit] [{2}]", DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"), ip, GetIpPosition(ip)));
                    }
                    catch { }
                    finally
                    {
                        sw.Close();
                    }