简体   繁体   中英

Is it possible in c# to write a binary file with a file size that is not divisible by 4?

I am trying to use c# to create a binary file (which I am using to mod a game) that is 506 KB. However, no matter what I try, the file size always comes out to be something divisible by 4 (which 506 is unfortunately not). For example, I have gotten the resulting file to be 504 KB. I have gotten it to be 508 KB. However, I can not get it to be 506 KB. Is there a way to make it so that your resulting file size does not have to be divisible by 4? Here is an example of something that I've tried (that still ends up yielding a file of size 504 KB):

int k = 1024 * 506; //because there are 1024 bytes in a KB and I want 506 KB` `

 BinaryWriter writer = new BinaryWriter(System.IO.File.OpenWrite("path"));
            
 for(int i = 0; i < k; i++)`
 {
   writer.Write(Convert.ToByte(false));
 }   

My guess for this is that you've written your file to a disk that has 4kb clusters:

在此处输入图像描述

Incidentally, File.WriteAllBytes(path, new byte[506 * 1024]) is possibly a more succinct and performant way to write exactly 518144 zero bytes to disk, than one-by-one'ing conversion of false to byte..

I just tried adding writer.close() to my code and that worked like a charm. I got the 506 KB file that I needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM