Microsoft KB Archive/327265

= PRB: File Is Not Written to Disk If You Do Not Call the StreamWriter.Close Method =

Article ID: 327265

Article Last Modified on 10/30/2003

-

APPLIES TO


 * Microsoft .NET Framework Class Libraries 1.0
 * Microsoft .NET Framework Class Libraries 1.1

-



This article was previously published under Q327265



SYMPTOMS
If you do not call the Close method of the StreamWriter class, the contents of the file are not written to the disk, even after the object is destroyed.



RESOLUTION
The developer is responsible to explicitly call the Close method of the StreamWriter class to flush the contents of the file to disk.

To work around this problem, use one of the following methods:
 * Dispose the StreamWriter object to cause the Close method to be called internally.
 * Set the AutoFlush property of the StreamWriter object to True, which causes each write operation to be immediately flushed to disk.

Sample Code
The following C# code demonstrates this problem and each of the workarounds listed earlier in this article. using System.IO;

public class Test {  public static void Main {     Test t = new Test;

t.GoodWrite1; //Using Close t.GoodWrite2; //Using Dispose t.GoodWrite3; //Using AutoFlush t.BadWrite;  //None of the above }

public void GoodWrite1 {     StreamWriter writer = new StreamWriter(&quot;file1.txt&quot;, true); writer.WriteLine(&quot;A line of Text from GoodWrite1.&quot;); //Close the StreamWriter to flush the data. writer.Close; writer = null; }

public void GoodWrite2 {     //The USING statement defines a scope for the StreamWriter object. //At the end of the scope, the object will be disposed. This //causes the Close method to be called internally. using (StreamWriter writer = new StreamWriter(&quot;file2.txt&quot;, true)) {        writer.WriteLine(&quot;A line of Text from GoodWrite2.&quot;); }  }

public void GoodWrite3 {     StreamWriter writer =  new StreamWriter(&quot;file3.txt&quot;, true); //Force a data flush after every WriteLine. writer.AutoFlush = true; writer.WriteLine(&quot;A line of Text from GoodWrite3.&quot;); writer = null; }

public void BadWrite {     //The contents of the file is not written to the disk //if the Close method is not called. StreamWriter writer = new StreamWriter(&quot;file0.txt&quot;, true); writer.WriteLine(&quot;A line of Text from BadWrite.&quot;); writer = null; } }



STATUS
This behavior is by design.

Keywords: kbkernbase kbprb kbpending kbfileio KB327265

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.