Why Does The Size Of Binary File Does Not Decrease While Using BinaryWriter

Why does the size Of a binary file not decrease while using BinaryWriter? Consider this first piece of code:

static void write()
{
    BinaryWriter sr = new BinaryWriter(File.OpenWrite("bin.txt"));
    int m;
    m = 123456;
    sr.Write(m);
    m = 122;
    sr.Write(m);
    sr.Close();
}

While using the above method the size of bin.txt is 8 bytes.

But when I remove m = 122 and the second Write call from the function and run the program again, I expect the file size to be changed to 4 bytes, but it's still 8 bytes.

static void write()
{
    BinaryWriter sr = new BinaryWriter(File.OpenWrite("bin.txt"));
    int m;
    m = 123456;
    sr.Write(m);
    sr.Close();
}

While Running Below Function By Adding double Type In It Than The Size Of File Increases From 8 To 12 .

static void write()
{
    BinaryWriter sr = new BinaryWriter(File.OpenWrite("bin.txt"));
    int m;
    m = 123456;
    sr.Write(m);
    double pp = 1233.00;
    sr.Write(pp);
    sr.Close();
}
Jon Skeet
people
quotationmark

This has nothing to do with BinaryWriter, really - it's the File.OpenWrite call, whose documentation includes:

The OpenWrite method opens a file if one already exists for the file path, or creates a new file if one does not exist. For an existing file, it does not append the new text to the existing text. Instead, it overwrites the existing characters with the new characters. If you overwrite a longer string (such as "This is a test of the OpenWrite method") with a shorter string (such as "Second run"), the file will contain a mix of the strings ("Second runtest of the OpenWrite method").

So your second method does only write four bytes - but it overwrites the first four bytes of the file without truncating the file itself.

Use File.Create instead, and any existing file will be truncated.

I'd also advise you to use using statements instead of closing resource manually:

using (var writer = new BinaryWriter(File.Create("foo"))
{
    // Code here, no need to call writer.Close()
}

people

See more on this question at Stackoverflow