Click here to Skip to main content
15,888,521 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Why The File Size Does Not Decreases To 4byte While Removing Int From 2nd Method.
C#
 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 Above Function The Size Of bin.txt Is 8 Byte .

But While Removing m = 122 From The Below Function And Running The Same program Again  , The File Size Has To Be Changed 4Byte , But It Is Not Changing 4 Byte .It Is Being Same As 8 Byte   
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 Of Size 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();
        }


Why The File Size Does Not Decreases To 4byte While Removing Int From 2nd Method
Posted
Updated 17-Dec-15 22:25pm
v2
Comments
BillWoodruff 18-Dec-15 4:35am    
Consider that there may be a minimum allocated size for the binary stream ?
BillWoodruff 18-Dec-15 4:37am    
This is in effect a repost: you should add this content to your first question posted only a few hours ago, then delete this post.
Jochen Arndt 18-Dec-15 4:45am    
Too late. I have just answered it without recognizing that it is a repost.

1 solution

That happens because you are writing to an already existing file that has a larger size than the data you are writing. From the OpenWrite[^] description:
Quote:
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”).

If you create a new file or delete it before, the size will be 4.

[UPDATE]
If you want existing files to be truncated, use File.Open() with the appropiate mode or just File.Create()[^]:
C#
BinaryWriter sr = new BinaryWriter(File.Create("bin.txt"));

File.OpenWrite() uses FileMode.OpenOrCreate while File.Create() uses FileMode.Create. See FileMode[^] for a description of the modes.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900