public static void WritePortableExecutable(PortableExecutableInfo peInfo, Stream stream) { var writer = new BinaryWriter(stream); peInfo.WritePortableExecutable(writer); writer.Close(); }
public static void WritePortableExecutable(PortableExecutableInfo peInfo, string path) { FileSystemUtils.ClearReadOnlyAttribute(path); var stream = new FileStream(path, FileMode.Create, FileAccess.ReadWrite); WritePortableExecutable(peInfo, stream); stream.Close(); }
public static List <string> GetDependencies(string path) { var result = new List <string>(); var peInfo = new PortableExecutableInfo(path); var dir = peInfo.ImportDirectory; if (dir != null) { var reader = GetBinaryReader(path); foreach (var desc in dir.Descriptors) { var fileNameOffset = peInfo.GetOffsetFromRVA(desc.NameRVA); reader.BaseStream.Seek(fileNameOffset, SeekOrigin.Begin); var fileName = BinaryReaderUtils.ReadNullTerminatedAsciiString(reader); result.Add(fileName); } reader.Close(); } return(result); }
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); }