-4

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"?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
prototype0815
  • 592
  • 2
  • 7
  • 24
  • 1
    What do you mean by _comfortable_? Why do you think this is _uncomfortable_? – Soner Gönül Jan 18 '16 at 13:34
  • 2
    Just use [`file.WriteLine()`](https://msdn.microsoft.com/en-us/library/ebb1kw70(v=vs.110).aspx) instead of `file.WriteLine("\r\n")`. – Tim Schmelter Jan 18 '16 at 13:34
  • 1
    You should also use a 'using' statement as StreamWriter implements IDisposable. – C. Knight Jan 18 '16 at 13:35
  • 4
    Indeed - and this is only pseudo-code anyway, given that you don't actually have a string literal in the first line, and the call would be to `Close`, not `close`. It's helpful to put *real* code in a question rather than pseudo-code, where possible. – Jon Skeet Jan 18 '16 at 13:38

2 Answers2

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If your only concern is the line endings, you can use a single, empty WriteLine() (which uses Environment.NewLine, which takes the line end representation for that OS):

file.WriteLine();

Besides that, StreamWriter is a good way to write to a file, and it is pretty easy too. If you prefer long string concatenation and writing at once, File.WriteAllText is an option.

And don't forget the using statement to dispose your resources:

using (StreamWriter file = new StreamWriter(C:\Downloads\test.txt))
{
    // ... your code
}
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325