3

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?

5
  • 2
    Works fine for me. How are you displaying x? Commented Feb 11, 2014 at 2:10
  • I am just displaying x in message box. Commented Feb 11, 2014 at 2:16
  • What happens when you debug the code and step over the ReadInt32 line.. does x hold 10? Commented Feb 11, 2014 at 2:17
  • 1) Try Encoding.UTF8 instead. 2) Set the offset to 0 explicitly. Commented Feb 11, 2014 at 2:23
  • No x holds the same value which it displays..@Itachi I am supposed to use Encode.Unicode only . Is there any other any other way which can be used ? Commented Feb 11, 2014 at 2:42

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.