-1

我有一个控制台应用程序,它将已处理作业的详细信息写入 .txt 文件。我使用这段代码来做到这一点:

StreamWriter jp = new StreamWriter(jobsProcessed);
jp.WriteLine(DateTime.Now.ToString());
jp.WriteLine(info);
jp.WriteLine("------");
jp.Close();

不幸的是,每次处理作业时,新的“信息”字符串都会替换前一个。有什么方法可以将新文本添加到文本文件的末尾或开头?

4

5 回答 5

2
StreamWriter jp = new StreamWriter(jobsProcessed,true);

第二个参数

//Determines whether data is to be appended to the file. If the file exists
//and append is false, the file is overwritten. If the file exists and append
// is true, the data is appended to the file. Otherwise, a new file is created.

http://www.dotnetperls.com/streamwriter http://social.msdn.microsoft.com/Forums/zh/clr/thread/17cd8ccf-7e53-41de-b4cc-221da70405a4

于 2013-01-17T11:22:14.030 回答
2

您可以使用StreamWriter Constructor (String, Boolean),其中第二个布尔参数表示数据是否必须附加到已经可用的数据。

并且还要避免调用Close和使用using语句

using(StreamWriter jp = new StreamWriter(jobsProcessed))
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
   //jp.Close(); //NO NEED MORE
}

这样做的好处是,即使发生异常(可能发生),顺便说一下,流也会是Disposed

于 2013-01-17T11:23:00.843 回答
2

StreamWriter 构造函数有一个重载,它接受第二个参数append;

using (StreamWriter jp = new StreamWriter(jobsProcessed, true))
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
}

将您的 StreamWriter 包装在using上面的块中也是更好的做法。

于 2013-01-17T11:24:06.020 回答
1

只需修改这个:

StreamWriter jp = new StreamWriter(jobsProcessed);

对此:

StreamWriter jp = new StreamWriter(jobsProcessed, true);
于 2013-01-17T11:23:12.677 回答
0
// using (StreamWriter jp = new StreamWriter(jobsProcessed)) Overwrites, not good for you!
using (StreamWriter jp = new StreamWriter(jobsProcessed, true)) // Appends, good for you!
{
    jp.WriteLine(DateTime.Now.ToString());
    jp.WriteLine(info);
    jp.WriteLine("------");
}

但是你可以像这样简化你的代码:

String[] content = File.ReadAllLines(jobsProcessed);

String[] newContent = new String[3];
newContent[0] = DateTime.Now.ToString();
newContent[1] = info;  
newContent[2] = "------";

File.AppendAllLines(jobsProcessed, newContent);
于 2013-01-17T11:26:34.750 回答