4

I received some data (many times) which are encapsulated inside a struct. what I need to do is write them to a file (binary) to restore the data. how will you do it?

5YrsLaterDBA
  • 33,370
  • 43
  • 136
  • 210
  • You may want to look at this: http://stackoverflow.com/questions/628843/byte-for-byte-serialization-of-a-struct-in-c – James Black Jul 30 '10 at 13:36
  • Do you need to write it in a specific format (e.g. to be read by another program) or just so you can save some status and read it again from the same program? In the later case I would suggest declaring the struct [serializable] (and all custom member types) and just serialize it to the file. – Grizzly Jul 30 '10 at 13:37
  • 1
    I was going to Answer "Let me Google that for you" but I may get to many upvotes... – Luiscencio Jul 30 '10 at 13:45

2 Answers2

6

Implement ISerializable (greater customization) or mark with the [Serializable] attribute (easier to use). Then use a BinaryFormatter to serialize to a file.

AllenG
  • 8,112
  • 29
  • 40
1
public struct MyStruct : ISerializable
    {
        #region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            throw new NotImplementedException();
        }

        #endregion

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public static bool operator ==(MyStruct m1, MyStruct m2)
        {
            return true;
        }

        public static bool operator !=(MyStruct m1, MyStruct m2)
        {
            return false;
        }
    }
garik
  • 5,669
  • 5
  • 30
  • 42