private void ReadImageNTHeaders() { // Calculate the offset where the IMAGE_OPTIONAL_HEADER starts UInt32 imageOptionalHeaderOffset = ImageNTHeadersOffset + 4 + (UInt32)Marshal.SizeOf <IMAGE_FILE_HEADER>(); using (FileStream stream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (BinaryReader reader = new BinaryReader(stream)) { reader.BaseStream.Seek(imageOptionalHeaderOffset, SeekOrigin.Begin); // Retrieve the Magic field and then read the appropriate (32-bit or 64-bit) IMAGE_NT_OPTIONAL_HEADER OptionalHeaderMagic = (ImageOptionalHeaderMagic)reader.ReadUInt16(); if (OptionalHeaderMagic == ImageOptionalHeaderMagic.IMAGE_NT_OPTIONAL_HDR32_MAGIC) { ImageNTHeaders32 = IMAGE_NT_HEADERS32.Read(Path, ImageDosHeader.e_lfanew); FirstImageSectionHeaderOffset = ImageNTHeadersOffset + (UInt32)Marshal.SizeOf <IMAGE_NT_HEADERS32>(); NumberOfImageSectionHeaders = ImageNTHeaders32.FileHeader.NumberOfSections; } else if (OptionalHeaderMagic == ImageOptionalHeaderMagic.IMAGE_NT_OPTIONAL_HDR64_MAGIC) { ImageNTHeaders64 = IMAGE_NT_HEADERS64.Read(Path, ImageDosHeader.e_lfanew); FirstImageSectionHeaderOffset = ImageNTHeadersOffset + (UInt32)Marshal.SizeOf <IMAGE_NT_HEADERS64>(); NumberOfImageSectionHeaders = ImageNTHeaders64.FileHeader.NumberOfSections; } } }
/// <summary> /// Reads the <see cref="IMAGE_NT_HEADERS64"/> structure from a file, starting at a specific offset /// </summary> /// <param name="path">The file to read</param> /// <param name="headerOffset">The offset in the file from where the structure will be read.</param> /// <returns></returns> public static IMAGE_NT_HEADERS64 Read(string path, UInt32 headerOffset) { if (path == null) { throw new ArgumentNullException("path"); } using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (BinaryReader reader = new BinaryReader(stream)) { reader.BaseStream.Seek(headerOffset, SeekOrigin.Begin); IMAGE_NT_HEADERS64 imageNTHeaders64 = new IMAGE_NT_HEADERS64(); imageNTHeaders64.Signature = reader.ReadUInt32(); imageNTHeaders64.FileHeader = ImageFileHeader.Read(reader); imageNTHeaders64.OptionalHeader64 = ImageOptionalHeader64.Read(reader); return(imageNTHeaders64); } }