2

I have a problem with data alignment in a file that I am creating from C# to be used in a legacy app.

I have all my data stored as a List of structs.

 List<CParameterItem> m_Items = new List<CParameterItem>();

where the CParameterItem looks like:

[StructLayout( LayoutKind.Sequential,Pack = 2 )]
public struct CParameterItem
{
    public byte ParamID;
    public ushort Size;
    public byte[] Data;
}

When I try and iterate the collection and write them to file, I have byte alignment problems between each item (byte alignment within each struct is correct).

BinaryWriter bw = new BinaryWriter( File.Open( theFilename, FileMode.CreateNew ) );
        foreach ( CParameterItem param in m_Items )
        {
            bw.Write( param.ParamID );
            bw.Write( param.Size );
            bw.Write( param.Data );
        }
        bw.Close();

Any ideas how to sort out the packing between items? Many thanks.

  • 1
    Pretty unclear, but there is no alignment when you use BinaryWriter. Everything is tightly packed, equivalent to Pack = 1. The Data array size matters, sounds like Size should be written but not be present in the struct, using Data.Length instead. You can get any alignment or size you want by writing the padding yourself. – Hans Passant Mar 14 '12 at 11:26

0 Answers0