Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a text file in C#

I need to write a strings into a text file from C#, each string on a new line...How can I do this?

like image 361
Nevin Mathai Avatar asked Dec 02 '22 06:12

Nevin Mathai


2 Answers

You can use File.WriteAllLines:

string[] mystrings = new string[] { "Foo", "Bar", "Baz", "Qux" };

System.IO.File.WriteAllLines("myfile.txt", mystrings);
like image 102
dtb Avatar answered Dec 21 '22 11:12

dtb


If you wish to append the text lines to the file, use AppendAllText:

string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
like image 22
SwDevMan81 Avatar answered Dec 21 '22 11:12

SwDevMan81