public static void WritePortableExecutable(PortableExecutableInfo peInfo, Stream stream) { var writer = new BinaryWriter(stream); peInfo.WritePortableExecutable(writer); writer.Close(); }
public static void RenameDependencyFileName(string filePath, string oldFileName, string newFileName) { if (oldFileName.Length != newFileName.Length) { throw new NotImplementedException( "when renaming dependencies, old file name must have the same size as new file name"); } var peInfo = new PortableExecutableInfo(filePath); uint oldNameRVA = 0; PESectionHeader header = null; var sectionIndex = -1; foreach (var descriptor in peInfo.ImportDirectory.Descriptors) { var nameRVA = descriptor.NameRVA; header = peInfo.FindSectionByRVA(nameRVA); if (header != null) { sectionIndex = peInfo.SectionHeaders.IndexOf(header); var fileNameAddressInSection = PortableExecutableInfo.GetAddressInSectionFromRVA(header, nameRVA); var fileName = ReadNullTerminatedAsciiString(peInfo.Sections[sectionIndex], fileNameAddressInSection); if (fileName.Equals(oldFileName, StringComparison.InvariantCultureIgnoreCase)) { oldNameRVA = nameRVA; } } } if (oldNameRVA > 0) { var newFileNameAsciiBytes = Encoding.ASCII.GetBytes(newFileName); var addressInSection = PortableExecutableInfo.GetAddressInSectionFromRVA(header, oldNameRVA); var section = peInfo.Sections[sectionIndex]; Buffer.BlockCopy(newFileNameAsciiBytes, 0, section, (int)addressInSection, newFileNameAsciiBytes.Length); } PortableExecutableInfo.WritePortableExecutable(peInfo, filePath); }