// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.IO; using System.Runtime.InteropServices; namespace E { [StructLayout(LayoutKind.Sequential,CharSet=CharSet.Ansi,Pack=1)] public struct TFooBar { private byte alen; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=10)] public string a; private byte blen; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=20)] public string b; private byte clen; [MarshalAs(UnmanagedType.ByValTStr,SizeConst=30)] public string c; } public class Program { public static void Main(string[] args) { Stream stm = new FileStream(@"C:\foobar.dat", FileMode.Open, FileAccess.Read); TFooBar[] data = new TFooBar[4]; int bufsiz = Marshal.SizeOf(typeof(TFooBar)); byte[] b = new byte[bufsiz]; IntPtr buf = Marshal.AllocHGlobal(bufsiz); for(int i = 0; i < data.Length; i++) { stm.Read(b, 0, b.Length); Marshal.Copy(b, 0, buf, b.Length); data[i] = (TFooBar)Marshal.PtrToStructure(buf, typeof(TFooBar)); } Marshal.FreeHGlobal(buf); stm.Close(); for(int i = 0; i < data.Length; i++) { Console.WriteLine(data[i].a + " " + data[i].b + " " + data[i].c); } } } }