Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Naive OLE file header parser based on inline AAF spec comments from olefile
using System;
using System.IO;
using System.Runtime.InteropServices;
public class OleReader
{
public OleReader(string filename, long offset = 0L)
{
if (string.IsNullOrWhiteSpace(filename))
{
throw new ArgumentNullException("filename");
}
if (!File.Exists(filename))
{
throw new IOException("File '" + filename + "' not found");
}
if (offset < 0L)
{
throw new ArgumentOutOfRangeException("offset");
}
this.reader = new BinaryReader(File.OpenRead(filename));
this.offset = offset;
}
public OleHeader ParseHeader()
{
byte[] readBuffer = this.reader.ReadBytes(512);
OleHeader result;
GCHandle handle;
try
{
handle = GCHandle.Alloc(readBuffer, GCHandleType.Pinned);
result = (OleHeader)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(OleHeader));
}
finally
{
handle.Free();
}
return result;
}
private BinaryReader reader;
private long offset;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, Size = 4)]
public struct FATEntry
{
[MarshalAs(UnmanagedType.I1)]
public byte A;
[MarshalAs(UnmanagedType.I1)]
public byte B;
[MarshalAs(UnmanagedType.I1)]
public byte C;
[MarshalAs(UnmanagedType.I1)]
public byte D;
}
[StructLayout(LayoutKind.Explicit)]
public struct OleHeader
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] MagicBytes;
[FieldOffset(8)]
[MarshalAs(UnmanagedType.Struct)]
public Guid CLSID;
[FieldOffset(24)]
[MarshalAs(UnmanagedType.U2)]
public ushort MinorVersion;
[FieldOffset(26)]
[MarshalAs(UnmanagedType.U2)]
public ushort DllVersion;
[FieldOffset(28)]
[MarshalAs(UnmanagedType.U2)]
public ushort ByteOrder;
[FieldOffset(30)]
[MarshalAs(UnmanagedType.U2)]
public ushort SectorShift;
[FieldOffset(32)]
[MarshalAs(UnmanagedType.U2)]
public ushort MiniSectorShift;
[FieldOffset(34)]
[MarshalAs(UnmanagedType.U2)]
public ushort Reserved;
[FieldOffset(36)]
[MarshalAs(UnmanagedType.U4)]
public int Reserved1;
[FieldOffset(40)]
[MarshalAs(UnmanagedType.U4)]
public int SectDir;
[FieldOffset(44)]
[MarshalAs(UnmanagedType.U4)]
public int SectCount;
[FieldOffset(48)]
[MarshalAs(UnmanagedType.U4)]
public int SectDirStart;
[FieldOffset(52)]
[MarshalAs(UnmanagedType.U4)]
public int Signature;
[FieldOffset(56)]
[MarshalAs(UnmanagedType.U4)]
public int MiniSectorCutoff;
[FieldOffset(60)]
[MarshalAs(UnmanagedType.U4)]
public int SectMiniFatStart;
[FieldOffset(64)]
[MarshalAs(UnmanagedType.U4)]
public int SectMiniFat;
[FieldOffset(68)]
[MarshalAs(UnmanagedType.U4)]
public int SectDifStart;
[FieldOffset(72)]
[MarshalAs(UnmanagedType.U4)]
public int SectDif;
[FieldOffset(76)]
[MarshalAs(UnmanagedType.Struct)]
public FATEntry FATHead;
[FieldOffset(80)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 432)]
public byte[] FATs;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.