Nav apraksta
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Image.cs 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. using System;
  6. using System.IO;
  7. namespace Microsoft.Unity.VisualStudio.Editor
  8. {
  9. public sealed class Image : IDisposable
  10. {
  11. long position;
  12. Stream stream;
  13. Image(Stream stream)
  14. {
  15. this.stream = stream;
  16. this.position = stream.Position;
  17. this.stream.Position = 0;
  18. }
  19. bool Advance(int length)
  20. {
  21. if (stream.Position + length >= stream.Length)
  22. return false;
  23. stream.Seek(length, SeekOrigin.Current);
  24. return true;
  25. }
  26. bool MoveTo(uint position)
  27. {
  28. if (position >= stream.Length)
  29. return false;
  30. stream.Position = position;
  31. return true;
  32. }
  33. void IDisposable.Dispose()
  34. {
  35. stream.Position = position;
  36. }
  37. ushort ReadUInt16()
  38. {
  39. return (ushort)(stream.ReadByte()
  40. | (stream.ReadByte() << 8));
  41. }
  42. uint ReadUInt32()
  43. {
  44. return (uint)(stream.ReadByte()
  45. | (stream.ReadByte() << 8)
  46. | (stream.ReadByte() << 16)
  47. | (stream.ReadByte() << 24));
  48. }
  49. bool IsManagedAssembly()
  50. {
  51. if (stream.Length < 318)
  52. return false;
  53. if (ReadUInt16() != 0x5a4d)
  54. return false;
  55. if (!Advance(58))
  56. return false;
  57. if (!MoveTo(ReadUInt32()))
  58. return false;
  59. if (ReadUInt32() != 0x00004550)
  60. return false;
  61. if (!Advance(20))
  62. return false;
  63. if (!Advance(ReadUInt16() == 0x20b ? 222 : 206))
  64. return false;
  65. return ReadUInt32() != 0;
  66. }
  67. public static bool IsAssembly(string file)
  68. {
  69. if (file == null)
  70. throw new ArgumentNullException("file");
  71. using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  72. return IsAssembly(stream);
  73. }
  74. public static bool IsAssembly(Stream stream)
  75. {
  76. if (stream == null)
  77. throw new ArgumentNullException(nameof(stream));
  78. if (!stream.CanRead)
  79. throw new ArgumentException(nameof(stream));
  80. if (!stream.CanSeek)
  81. throw new ArgumentException(nameof(stream));
  82. using (var image = new Image(stream))
  83. return image.IsManagedAssembly();
  84. }
  85. }
  86. }