BinaryWriter not writing to file

Viewed 146

I am trying to write data files to disk so that I can cache large amounts of data that won't fit into memory. In some early tests I find that sometimes I get data written and sometimes not. Here is a sample that shows the process not working:

using System.IO;
using System;


namespace TestBinaryWriter
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            double dFoo = 1234.1234;
            BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"));
            bw.Write(dFoo);
            bw.Write(BitConverter.GetBytes(dFoo));
        }
    }
}

The contents of file 'asdf' are empty and I don't understand why.

3 Answers

Initialize and use BinaryWriter in using block:

using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"))
{
    bw.Write(dFoo);
    bw.Write(BitConverter.GetBytes(dFoo));
}

What was wrong with your implementation was that the Stream was not closed (by calling close method) and contents were not properly flushed into the file.

With the using statement, it will automatically cause the Dispose method to be called. In the Dispose implementation, Close is called. This is how it works.

BinaryWriter caches the data, to write data to the file yous should either do it explicitly

  ...
  bw.Write(dFoo);
  bw.Flush(); // <- write all the data (dFoo) down
  ...

or Close (Dispose) the writer. Typical pattern is using:

{
  ...

  // bw will be closed on leaving its scope  
  using BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"));

  bw.Write(dFoo);
  bw.Write(BitConverter.GetBytes(dFoo));
  ...
} // bw will be closed here (with all data cached being written)

Or

  using (BinaryWriter bw = new BinaryWriter(File.OpenWrite("asdf"))) {
    bw.Write(dFoo);
    bw.Write(BitConverter.GetBytes(dFoo)); 
  } // bw will be closed here (with all data cached being written)

Try enclosing the declaration and usage of the bw variable in a using statement so that it is automatically disposed (and therefore flushed) before exiting the program.

Related