I'm pretty new in developing C#, and my problem is to write a text file. I found some solution with StreamWriter lik this...
StreamWriter file = new StreamWriter("C:\Downloads\test.txt");
file.WriteLine("this is line one");
file.WriteLine("\r\n");
file.WriteLine("this is line 2");
file.Close();
Is there a more comfortable way to write a file? Maybe without the hardcoded "\r\n"
?
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.
See more on this question at Stackoverflow