/src/LinFu.Reflection.Emit/AssemblyDefinitionExtensions.cs
C# | 58 lines | 30 code | 5 blank | 23 comment | 0 complexity | d84efa0b17d58fedb75ea5c94d2548d6 MD5 | raw file
1using System.IO; 2using System.Reflection; 3using Mono.Cecil; 4 5namespace LinFu.Reflection.Emit 6{ 7 /// <summary> 8 /// A class that adds extension methods to the <see cref="AssemblyDefinition" /> 9 /// class. 10 /// </summary> 11 public static class AssemblyDefinitionExtensions 12 { 13 /// <summary> 14 /// Converts an <see cref="AssemblyDefinition" /> 15 /// into a running <see cref="Assembly" />. 16 /// </summary> 17 /// <param name="definition">The <see cref="AssemblyDefinition" /> to convert.</param> 18 /// <returns> 19 /// An <see cref="Assembly" /> that represents the <see cref="AssemblyDefinition" /> instance. 20 /// </returns> 21 public static Assembly ToAssembly(this AssemblyDefinition definition) 22 { 23 Assembly result = null; 24 using (var stream = new MemoryStream()) 25 { 26 // Persist the assembly to the stream 27 definition.Save(stream); 28 var buffer = stream.GetBuffer(); 29 result = Assembly.Load(buffer); 30 } 31 32 return result; 33 } 34 35 /// <summary> 36 /// Saves the assembly to disk. 37 /// </summary> 38 /// <param name="definition">The target assembly definition.</param> 39 /// <param name="filename">The output file name.</param> 40 public static void Save(this AssemblyDefinition definition, string filename) 41 { 42 var memoryStream = new MemoryStream(); 43 definition.Save(memoryStream); 44 45 File.WriteAllBytes(filename, memoryStream.ToArray()); 46 } 47 48 /// <summary> 49 /// Saves the assembly to disk. 50 /// </summary> 51 /// <param name="definition">The target assembly definition.</param> 52 /// <param name="outputStream">The destination file stream.</param> 53 public static void Save(this AssemblyDefinition definition, Stream outputStream) 54 { 55 definition.Write(outputStream); 56 } 57 } 58}