public static PortableExecutableFileHeader Read(string peFilePath) { var peFileHeader = new PortableExecutableFileHeader() { IsValid = false, DosHeader = null, NtHeader = null, }; // Read DOS header. var dosHeader = ImageDosHeader.Read(peFilePath); if (!dosHeader.IsValid) { return(peFileHeader); } // Read NT header. var ntHeader = ImageNtHeaders.Read(peFilePath, dosHeader.e_lfanew); if (!ntHeader.IsValid) { return(peFileHeader); } peFileHeader.IsValid = true; peFileHeader.DosHeader = dosHeader; peFileHeader.NtHeader = ntHeader; return(peFileHeader); }
internal static ImageNtHeaders Read(string filePath, int ntHeaderOffset) { var ntHeader = new ImageNtHeaders() { IsValid = false, Signature = 0, FileHeader = null, OptionalHeader = null, }; using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var reader = new BinaryReader(stream)) { // Read sigunature of NT header. reader.BaseStream.Seek(ntHeaderOffset, SeekOrigin.Begin); // Set position to the NT header. var signature = reader.ReadUInt32(); if (signature != ImageNtSignature) { return(ntHeader); } // Read file header. var fileHeader = ImageFileHeader.Read(reader); // Read optional header magic. var currentPosition = reader.BaseStream.Position; // Save current position. var optionalHeaderMagic = reader.ReadUInt16(); reader.BaseStream.Seek(currentPosition, SeekOrigin.Begin); // Restore position. ImageOptionalHeader optionalHeader; if (optionalHeaderMagic == NativeImageOptionalHeader.ImageNtOptionalHeader32Magic) { // Read optinal header as 32-bit. optionalHeader = ImageOptionalHeader32.Read(reader); } else if (optionalHeaderMagic == NativeImageOptionalHeader.ImageNtOptionalHeader64Magic) { // Read optinal header as 64-bit. optionalHeader = ImageOptionalHeader64.Read(reader); } else { return(ntHeader); } ntHeader.IsValid = true; ntHeader.Signature = signature; ntHeader.FileHeader = fileHeader; ntHeader.OptionalHeader = optionalHeader; return(ntHeader); } }