开发者

How to write a text file after the previous line in C#?

My be开发者_如何学编程low code creates a txt file and writes something to that file. But I need to write a new line after the previous lines when I run the script several times. Code:

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();

Current output on the abc.txt file:

Hi friends
csharpfriends is the new url for c-sharp

But I need the output if I run the script several times to be this:

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

How can I do that? Please help.


StreamWriter has a constructor which lets you append text instead of just writing into the file. The constructor is

new StreamWriter(string filepath, bool append)

If you set that bool to "true", then all writing will be at the end of the document. In your example...

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


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


Try this:

 System.IO.File.WriteAllText(@"file_location", System.IO.File.ReadAllText(@"file_location") + System.Environment.NewLine + "The_new_text");

That will add a new text to the next line.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜