title: Read binary file into a struct
body: <p>I'm trying to read binary data using C#. I have all the information about the layout of the data in the files I want to read. I'm able to read the data "chunk by chunk", i.e. getting the first 40 bytes of data converting it to a string, get the next 40 bytes.</p>
  
  <p>Since there are at least three slightly different version of the data, I would like to read the data directly into a struct. It just feels so much more right than by reading it "line by line".</p>
  
  <p><strong>I have tried the following approach but to no avail:</strong></p>
  
  <pre><code>StructType aStruct;
  int count = Marshal.SizeOf(typeof(StructType));
  byte[] readBuffer = new byte[count];
  BinaryReader reader = new BinaryReader(stream);
  readBuffer = reader.ReadBytes(count);
  GCHandle handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
  aStruct = (StructType) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(StructType));
  handle.Free();
  </code></pre>
  
  <p>The stream is an opened FileStream from which I have began to read from. I get an <code>AccessViolationExceptio</code>n when using <code>Marshal.PtrToStructure</code>.</p>
  
  <p>The stream contains more information than I'm trying to read since I'm not interested in data at the end of the file.</p>
  
  <p><strong>The struct is defined like:</strong></p>
  
  <pre><code>[StructLayout(LayoutKind.Explicit)]
  struct StructType
  {
      [FieldOffset(0)]
      public string FileDate;
      [FieldOffset(8)]
      public string FileTime;
      [FieldOffset(16)]
      public int Id1;
      [FieldOffset(20)]
      public string Id2;
  }
  </code></pre>
  
  <p>The examples code is changed from original to make this question shorter.</p>
  
  <p>How would I read binary data from a file into a struct?</p>