0

I am having some trouble writing a string MentionsInText to a file using the Systems.IO.StreamWriter according to the file it is edited when the code is run however, no text is present in the file. I am not sure why this is not working. My code is as follows;

 var MIS = string.Join(" ", MentionsList.ToArray());
 string Mentionsintext = MIS.ToString();

 StreamWriter MentionFile = new StreamWriter(@"C:\Users\User\Documents\Mentions.txt");

 MentionFile.WriteLine(Mentionsintext + Environment.NewLine);

Am I doing something wrong when using StreamWriter?

Rand Random
  • 7,300
  • 10
  • 40
  • 88
bdg
  • 465
  • 6
  • 18

1 Answers1

2

You should dispose of the StreamWriter after writing to it.

eg:

 var MIS = string.Join(" ", MentionsList.ToArray());
 string Mentionsintext = MIS.ToString();

 using (StreamWriter MentionFile = new StreamWriter(@"C:\Users\User\Documents\Mentions.txt")) {

      MentionFile.WriteLine(Mentionsintext + Environment.NewLine);

 }

For more examples: see https://www.dotnetperls.com/streamwriter

Nsevens
  • 2,588
  • 1
  • 17
  • 34
  • Thank you! from this would i be correct in saying that the same could be said for the use of `streamreader`? – bdg Nov 24 '17 at 07:51
  • 1
    @bdg You should always dispose of streams when you are finished with them. The easiest way of doing this is wrapping them in a `using(...)` statement as Nsevens suggested. In the example above, disposing of the stream causes `Flush()` to be called. In addition to doing this, it releases any unmanaged resources that the stream is using, thus preventing memory leaks. – ProgrammingLlama Nov 24 '17 at 08:05