title: What is the difference between StreamWriter.Flush() and StreamWriter.Close()?
body: <p>What is the difference in functionality between <code>StreamWriter.Flush()</code> and <code>StreamWriter.Close()</code>?</p>
  
  <p>When my data wasn't being written correctly to a file, I added both <code>Flush()</code> and <code>Close()</code> to the end of my code.  However, I realized that adding <em>either</em> <code>Flush()</code> or <code>Close()</code> allowed the data to be written correctly.</p>
  
  <p>I wasn't able to pick up on exactly what each of these methods does when I read the MSDN docs; I only figured out that one or the other is necessary to ensure data is written correctly. Any further explanation would be much appreciated.</p>
  
  <hr>
  
  <p>Where <code>s</code> is a string to be written, here's what my code looks like currently:</p>
  
  <pre><code>StreamWriter sw = File.CreateText("TextOutput.txt");
  sw.Write(s);
  sw.Flush();
  sw.Close();
  </code></pre>
  
  <hr>
  
  <p>Based on feedback from the answers, I've rewritten my code in a <code>using</code> block, which implements <code>IDisposable</code> and will automatically take care of writing the stream to the file when the object is disposed:</p>
  
  <pre><code>using (StreamWriter sw = File.CreateText("TextOutput.txt"))
  {
      sw.Write(s);
  }
  </code></pre>