EmbeddedResource.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // Author:
  3. // Jb Evain (jbevain@gmail.com)
  4. //
  5. // Copyright (c) 2008 - 2015 Jb Evain
  6. // Copyright (c) 2008 - 2011 Novell, Inc.
  7. //
  8. // Licensed under the MIT/X11 license.
  9. //
  10. using System;
  11. using System.IO;
  12. namespace ILRuntime.Mono.Cecil {
  13. public sealed class EmbeddedResource : Resource {
  14. readonly MetadataReader reader;
  15. uint? offset;
  16. byte [] data;
  17. Stream stream;
  18. public override ResourceType ResourceType {
  19. get { return ResourceType.Embedded; }
  20. }
  21. public EmbeddedResource (string name, ManifestResourceAttributes attributes, byte [] data) :
  22. base (name, attributes)
  23. {
  24. this.data = data;
  25. }
  26. public EmbeddedResource (string name, ManifestResourceAttributes attributes, Stream stream) :
  27. base (name, attributes)
  28. {
  29. this.stream = stream;
  30. }
  31. internal EmbeddedResource (string name, ManifestResourceAttributes attributes, uint offset, MetadataReader reader)
  32. : base (name, attributes)
  33. {
  34. this.offset = offset;
  35. this.reader = reader;
  36. }
  37. public Stream GetResourceStream ()
  38. {
  39. if (stream != null)
  40. return stream;
  41. if (data != null)
  42. return new MemoryStream (data);
  43. if (offset.HasValue)
  44. return new MemoryStream (reader.GetManagedResource (offset.Value));
  45. throw new InvalidOperationException ();
  46. }
  47. public byte [] GetResourceData ()
  48. {
  49. if (stream != null)
  50. return ReadStream (stream);
  51. if (data != null)
  52. return data;
  53. if (offset.HasValue)
  54. return reader.GetManagedResource (offset.Value);
  55. throw new InvalidOperationException ();
  56. }
  57. static byte [] ReadStream (Stream stream)
  58. {
  59. int read;
  60. if (stream.CanSeek) {
  61. var length = (int) stream.Length;
  62. var data = new byte [length];
  63. int offset = 0;
  64. while ((read = stream.Read (data, offset, length - offset)) > 0)
  65. offset += read;
  66. return data;
  67. }
  68. var buffer = new byte [1024 * 8];
  69. var memory = new MemoryStream ();
  70. while ((read = stream.Read (buffer, 0, buffer.Length)) > 0)
  71. memory.Write (buffer, 0, read);
  72. return memory.ToArray ();
  73. }
  74. }
  75. }