Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve integer value from binary file in C#

Tags:

c#

I am writing the integer value in binary file as follows:-

int val =10;

FileStream fs = new FileStream("BinaryFile.bin", FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs, Encoding.Unicode);

bw.Write(val);

//Reading value from binary as:-

FileStream fs = new FileStream("BinaryFile.bin", FileMode.Open);
  BinaryReader br = new BinaryReader(fs, Encoding.Unicode);

int x = br.ReadInt32();

Value retrieved is: 1.092616E + 09

I am getting this value instead of '10'

Is there any other method to retrieve the int value?

like image 686
Payal Avatar asked Dec 05 '25 04:12

Payal


1 Answers

Try by making change in BinaryWriter constructor

as

 FileStream fs = new FileStream("iram.bin", FileMode.Create);
        // Create the writer for data.
        BinaryWriter w = new BinaryWriter(fs);

w.Write((int) 2000);

w.Close();
fs.Close();

and read using

using (FileStream fs2 = new FileStream("iram.bin", FileMode.Open))
    {
        using(BinaryReader r = new BinaryReader(fs2))
        {
            var integerValue = r.ReadInt32();
        }
    }

More detail Writing to .bin binary file

like image 165
pg90 Avatar answered Dec 07 '25 16:12

pg90



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!