/src/LinFu.Reflection.Emit/AssemblyDefinitionExtensions.cs
C# | 58 lines | 30 code | 5 blank | 23 comment | 0 complexity | d84efa0b17d58fedb75ea5c94d2548d6 MD5 | raw file
- using System.IO;
- using System.Reflection;
- using Mono.Cecil;
- namespace LinFu.Reflection.Emit
- {
- /// <summary>
- /// A class that adds extension methods to the <see cref="AssemblyDefinition" />
- /// class.
- /// </summary>
- public static class AssemblyDefinitionExtensions
- {
- /// <summary>
- /// Converts an <see cref="AssemblyDefinition" />
- /// into a running <see cref="Assembly" />.
- /// </summary>
- /// <param name="definition">The <see cref="AssemblyDefinition" /> to convert.</param>
- /// <returns>
- /// An <see cref="Assembly" /> that represents the <see cref="AssemblyDefinition" /> instance.
- /// </returns>
- public static Assembly ToAssembly(this AssemblyDefinition definition)
- {
- Assembly result = null;
- using (var stream = new MemoryStream())
- {
- // Persist the assembly to the stream
- definition.Save(stream);
- var buffer = stream.GetBuffer();
- result = Assembly.Load(buffer);
- }
- return result;
- }
- /// <summary>
- /// Saves the assembly to disk.
- /// </summary>
- /// <param name="definition">The target assembly definition.</param>
- /// <param name="filename">The output file name.</param>
- public static void Save(this AssemblyDefinition definition, string filename)
- {
- var memoryStream = new MemoryStream();
- definition.Save(memoryStream);
-
- File.WriteAllBytes(filename, memoryStream.ToArray());
- }
- /// <summary>
- /// Saves the assembly to disk.
- /// </summary>
- /// <param name="definition">The target assembly definition.</param>
- /// <param name="outputStream">The destination file stream.</param>
- public static void Save(this AssemblyDefinition definition, Stream outputStream)
- {
- definition.Write(outputStream);
- }
- }
- }