By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,471 Members | 711 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,471 IT Pros & Developers. It's quick & easy.

How to use to read something using deserialization

P: 2
In this code, I write two ints to a binary file using Serialization. What I want to do is after writing them, read in only the second int. I should be able to just seek to 4 bytes past the beginning of the file, since each int is 4 bytes, but this won't work. Am I wrong in my understanding of seek?

Expand|Select|Wrap|Line Numbers
  1. FileStream serializeStream = new FileStream("test.bin", FileMode.Create);
  2. BinaryFormatter bf = new BinaryFormatter();
  4. int firstNum = 1111;
  5. int secondNum = 2222;
  7. serializeStream.Seek(0, SeekOrigin.Begin);
  8. bf.Serialize(serializeStream, firstNum);
  9. bf.Serialize(serializeStream, secondNum);
  10. serializeStream.Close();
  12. FileStream retrieveStream = new FileStream("test.bin", FileMode.Open);
  13. retrieveStream.Seek(4, SeekOrigin.Begin);
  14. int num= (int)bf.Deserialize(retrieveStream);
  15. Console.WriteLine("Number: " + num);
  16. retrieveStream.Close();
Jan 25 '09 #1
Share this Question
Share on Google+
3 Replies

Expert 100+
P: 190
I'm not sure if you chose BinaryFormatter because you thought you were writing data to a file in binary format, or for other reasons. I'm pretty sure the Serialize method will add metadata to the stream describing the object it is serializing - in this case a simple int, but an object that lives in an assembly nonetheless.
To confirm this, simply open the output file and see if it is longer than 8 bytes for the two ints.

I think what you might want is BinaryWriter Class (System.IO). This will write simple types directly to file, and you can then Seek and call ReadInt32() at the appropriate file position with a System.IO.BinaryReader.
Jan 26 '09 #2

Expert 100+
P: 190
Otherwise, to use BinaryFormatter as you are doing, you need to store each serialized object in its own stream and read the entire stream into the Deserializer to reconstitute the underlying Int32 object.
Serialization is a way to store an entire object as bits, and deserialization is a way to read those bits and reconstitute the object.
It is not just the value of the object stored as bits, which is your assumption when you navigate to the fifth byte thinking it is the value of the second integer.
An Int32 represents four bytes of data in memory - which a BinaryReader/Writer understands.
Int32 is also an object with methods and properties - which is what serialization cares about.
Jan 26 '09 #3

P: 2
Thank you. I'm not very familiar with writing to binary, but I understand what I need to do now.
Jan 26 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Browse more C# / C Sharp Questions on Bytes