本文介绍了使用BinaryWriter时,为什么二进制文件的大小不会减少的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么从第二种方法中删除Int时文件大小不会减少到4byte。

Why The File Size Does Not Decreases To 4byte While Removing Int From 2nd Method.

 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();
        }





为什么从第二种方法中删除Int时文件大小不会减少到4byte



Why The File Size Does Not Decreases To 4byte While Removing Int From 2nd Method

推荐答案

Quote:

如果你覆盖一个更长的字符串(例如这是一个使用较短的字符串(例如Second run)测试OpenWrite方法,该文件将包含混合字符串(OpenWrite方法的第二次运行测试)。

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").



如果您之前创建新文件或删除它,则大小为4.



[更新]

如果您想要现有要截断的文件,使用适当模式的 File.Open()或只是 []:


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()[^]:

BinaryWriter sr = new BinaryWriter(File.Create("bin.txt"));



File.OpenWrite()使用 FileMode.OpenOrCreate File.Create()使用 FileMode.Create 。请参阅 []了解模式的描述。


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


这篇关于使用BinaryWriter时,为什么二进制文件的大小不会减少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 09:56