The simplest approach for writing a multi-line file is File.WriteAllLines
:
File.WriteAllLines(@"c:\Downloads\test.txt",
new[] { "this is line one", "", "", "this is line 2" });
The empty strings are there because in your original code, you'd end with four lines of text... WriteLine
already adds a line separator, and you've got one explicitly in the middle call too. If you only want two lines (as per the specified contents) then you should use:
File.WriteAllLines(@"c:\Downloads\test.txt",
new[] { "this is line one", "this is line 2" });
That will use the platform-default line ending. If you don't want to use that, you could use string.Join
to join lines together however you want, then call File.WriteAllText
.
All File.*
methods dealing with text default to using UTF-8, but allow you to specify the encoding if you want something else.