PRB: File Is Not Written to Disk If You Do Not Call the StreamWriter.Close() Method (327265)
The information in this article 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("file1.txt", true);
writer.WriteLine("A line of Text from GoodWrite1.");
//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("file2.txt", true))
{
writer.WriteLine("A line of Text from GoodWrite2.");
}
}
public void GoodWrite3()
{
StreamWriter writer = new StreamWriter("file3.txt", true);
//Force a data flush after every WriteLine.
writer.AutoFlush = true;
writer.WriteLine("A line of Text from GoodWrite3.");
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("file0.txt", true);
writer.WriteLine("A line of Text from BadWrite.");
writer = null;
}
}
STATUSThis
behavior is by design.
Modification Type: | Minor | Last Reviewed: | 10/30/2003 |
---|
Keywords: | kbFileIO kbKernBase kbpending kbprb KB327265 kbAudDeveloper |
---|
|