How to write a text file in C#
Asked Answered
A

5

4

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

Assemblage answered 17/12, 2009 at 4:57 Comment(1)
Possible duplicate of Append lines to a file using a StreamWriterAfresh
S
13

You can use File.WriteAllLines:

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

System.IO.File.WriteAllLines("myfile.txt", mystrings);
Straggle answered 17/12, 2009 at 5:1 Comment(1)
+1; can't beat a one-liner! Exception handling not included. Available in .NET 2.0+. msdn.microsoft.com/en-us/library/…Crossarm
R
4

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);
Resolvable answered 17/12, 2009 at 5:53 Comment(0)
P
1

How about StreamWriter class? Read more here...

And do not forget about exception handling e.g missing file permissions etc.

Pongid answered 13/4, 2014 at 15:44 Comment(0)
C
0

Use the StreamWriter class; take a look at this tutorial. A new line is simply the character \n (Unix) or the characters \r\n (Windows).

Clea answered 17/12, 2009 at 5:1 Comment(0)
F
0

You can also use this sample into your code:

string myText = "This is my string";
System.IO.File.WriteAllText(@"C:\Users\Jack\source\repos\My Text.txt", myText);
Fivestar answered 11/2, 2023 at 9:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.