日期:2014-05-20  浏览次数:21032 次

如何向txt文件追加信息
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 ");
          }
}
这样每次有错误信息的写入的时候,都会覆盖上一次的信息,如何追加在后面而不是覆盖呢?

------解决方案--------------------
StreamWriter sw = File.CreateText(path+@ "\errorMessage.txt "))改为
StreamWriter sw = new StreamWriter(path+@ "\errorMessage.txt ",true)
------解决方案--------------------
使用重载的构造函数,指定追加方式为true
------解决方案--------------------
System.IO.StreamWriter sw = new System.IO.StreamWriter(path+@ "\errorMessage.txt ",true);
------解决方案--------------------
trt..

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

------解决方案--------------------
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();
}