title: StreamWriter Writing NUL characters at the end of the file when system shutdown abruptly
body: <p>I am writing some test application to write some text into a text file using <code>StreamWriter</code>. While executing the <code>WriteLine</code> method the system shuts down abruptly. After rebooting the machine I have observed that there are many NUL characters at the end of the file.</p>
  <p>I have searched many sites including MSDN and haven't found a solution to this problem.</p>
  <p>Could any one help me to resolve this problem?</p>
  <p>This can be easily reproduced if we do the following steps:</p>
  <ol>
  <li><p>Create WindowsApplication and place a button control on it.</p>
  </li>
  <li><p>In the button click event handler write the following code:</p>
  <p>private void button1_Click(object sender, EventArgs e)</p>
  <pre><code> {
       string str = &quot;Welcome to the C Sharp programming world with a test application using IO operations.&quot;;
       StreamWriter sw = new StreamWriter(fileName, true, Encoding.Unicode, str.Length);
       sw.WriteLine(str);
       sw.Close();        
   } 
  </code></pre>
  </li>
  <li><p>Run the application and click on the button continuously (Do not stop until machine shutdown) and press the Poweroff button of the PC.</p>
  </li>
  <li><p>Reboot the PC and check the file. It contains the following text:</p>
  </li>
  </ol>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>Welcome to the C Sharp programming world with a test application using IO operations.</p>
  <p>NULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNULNUL</p>
  <p>The NUL characters will appear in Notepaad++ and we cannot see these characters in normal Notepad.</p>