2010-05-25 130 views
0

我的下面的代码创建一个txt文件并将某些内容写入该文件。但是当我多次运行脚本时,我需要在前面的行之后写一行新行。代码:如何在C#中的前一行之后编写一个文本文件?

string filePath = "D:\\DOT_NET\\C#\\abc.txt"; 
FileInfo t = new FileInfo(filePath); 
StreamWriter Tex = t.CreateText(); 
Tex.WriteLine("Hi freinds"); 
Tex.WriteLine("csharpfriends is the new url for c-sharp"); 
Tex.Write(Tex.NewLine); 
Tex.Close(); 

abc.txt文件电流输出:

Hi friends 
csharpfriends is the new url for c-sharp 

但我需要的输出,如果我运行该脚本几次是这样的:

Hi friends 
csharpfriends is the new url for c-sharp 

Hi friends 
csharpfriends is the new url for c-sharp 

Hi friends 
csharpfriends is the new url for c-sharp 

我该怎么办那?请帮忙。

+2

首先,我认为你应该把StreamWriter声明放在一个using块中。 – 2010-05-25 12:39:49

回答

6

StreamWriter有一个构造函数,它允许您附加文本而不是只写入文件。构造函数是

new StreamWriter(string filepath, bool append) 

如果将该布尔值设置为“true”,则所有的写入操作都将在文档的末尾。在你的榜样......

StreamWriter Tex = new StreamWriter(@"D:\DOT_NET\C#\abc.txt", true); 
+0

谢谢你的回答,但是如果你想详细说明你的ans.pls指南,我将如何在我提到的代码中添加约束符。 谢谢 riad – riad 2010-05-25 12:41:33

+0

@riad将你当前的StreamWriter Tex声明替换为我在下面写道。你不必改变任何东西,因为你仍然可以正确关闭它。 – 2010-05-25 12:45:18

+1

有什么要详细说明的? @ccomet的回答中究竟* *的含义不明确? – 2010-05-25 12:46:06

2
using (StreamWriter sw = File.AppendText(path)) 
{ 
    sw.WriteLine("..."); 
} 
0

试试这个: System.IO.File.WriteAllText(@ “file_location”,System.IO.File.ReadAllText(@ “file_location”)+统环境.NewLine +“The_new_text”); 这段代码会改变你想要的var的行。

相关问题