I have the following C# code:
private const int APPENDBUFFERSIZE = 65536;
private StreamWriter _streamWriter;
private FileStream _fileStream;
private BufferedStream _bufferedStream;
public void Open(string fileName)
{
_fileStream = File.Open(fileName, FileMode.Create, FileAccess.Write, FileShare.Read);
_bufferedStream = new BufferedStream(_fileStream, APPENDBUFFERSIZE);
_streamWriter = new StreamWriter(_bufferedStream);
}
public void Write(string data)
{
_streamWriter.Write(data);
}
public void Close()
{
if (_streamWriter != null)
{
_streamWriter.Flush();
_streamWriter.Dispose();
_streamWriter = null;
}
if (_bufferedStream != null)
{
_bufferedStream.Dispose();
_bufferedStream = null;
}
if (_fileStream != null)
{
_fileStream.Dispose();
_fileStream = null;
}
}
Why doesn't the data get written to disk until I call Close? Technical data: I write 9000 KB worth of data
StreamWriter
class has:
internal const int DefaultBufferSize = 1024;
FileStream
class has:
internal const int DefaultBufferSize = 4096;
BufferedStream
should be 65536
bytes.
filename
is a full path to a file on my local drive D.
filename = "D:\\Folder1\Folder2\\file.txt"
And I do have permissions to write to it.
For a call to Write
I use something similar to:
data = "1234567889|ababababababababbabababababababababababab"
Also, I don't want to get rid of the buffer, I just want the stream to be flushed every now and then, and see it on disk. It's weird to have the file to 0 KB
and all of the sudden when you close, it's big.
So by all measurements, all the buffers should overflow unless written to next stream/disk. Still, Windows only shows file size greater than 0 KB
, after Close
, although I've waited a few minutes after the writing to file has finished.
Any ideas?
Thanks, Ciprian.
UPDATE: The size appears 0 in windows explorer size column. If I look at file properties, then the size is larger than 0(which is correct). After I return from the properties window and refresh the windows explorer window, the size column gets updated to a value larger than 0. I I just refresh the windows explorer window without looking at file properties, the size column stays at 0. Also if I open the file with notepad++, it has all the data, and a refresh on the windows explorer window shows the correct value in the size column. So my issue is probably not due to the code I wrote, but you never know.