![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /// <summary>运行时</summary> 2 public static class Runtime 3 { 4 #region 控制台 5 static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); 6 7 private static Boolean? _IsConsole; 8 /// <summary>是否控制台。用于判断是否可以执行一些控制台操作。</summary> 9 public static Boolean IsConsole 10 { 11 get 12 { 13 if (_IsConsole != null) return _IsConsole.Value; 14 15 IntPtr ip = Win32Native.GetStdHandle(-11); 16 if (ip == IntPtr.Zero || ip == INVALID_HANDLE_VALUE) 17 _IsConsole = false; 18 else 19 { 20 ip = Win32Native.GetStdHandle(-10); 21 if (ip == IntPtr.Zero || ip == INVALID_HANDLE_VALUE) 22 _IsConsole = false; 23 else 24 _IsConsole = true; 25 } 26 27 return _IsConsole.Value; 28 } 29 } 30 31 private static IntPtr _consoleOutputHandle; 32 private static IntPtr ConsoleOutputHandle 33 { 34 [SecurityCritical] 35 get 36 { 37 if (_consoleOutputHandle == IntPtr.Zero) _consoleOutputHandle = Win32Native.GetStdHandle(-11); 38 return _consoleOutputHandle; 39 } 40 } 41 42 /// <summary>获取PE文件类型。扩展方法</summary> 43 /// <param name="e"></param> 44 /// <returns></returns> 45 public static PEFileKinds GetPEFileKinds(this MemberInfo e) 46 { 47 return GetPEFileKinds(Path.GetFullPath(e.Module.Assembly.Location)); 48 49 } 50 51 /// <summary>Parses the PE header and determines whether the given assembly is a console application.</summary> 52 /// <param name="assemblyPath">The path of the assembly to check.</param> 53 /// <remarks>The magic numbers in this method are extracted from the PE/COFF file 54 /// format specification available from http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx 55 /// </remarks> 56 static PEFileKinds GetPEFileKinds(string assemblyPath) 57 { 58 using (var s = new FileStream(assemblyPath, FileMode.Open, FileAccess.Read)) 59 { 60 return GetPEFileKinds(s); 61 } 62 } 63 64 private static PEFileKinds GetPEFileKinds(Stream s) 65 { 66 var rawPeSignatureOffset = new byte[4]; 67 s.Seek(0x3c, SeekOrigin.Begin); 68 s.Read(rawPeSignatureOffset, 0, 4); 69 int peSignatureOffset = rawPeSignatureOffset[0]; 70 peSignatureOffset |= rawPeSignatureOffset[1] << 8; 71 peSignatureOffset |= rawPeSignatureOffset[2] << 16; 72 peSignatureOffset |= rawPeSignatureOffset[3] << 24; 73 var coffHeader = new byte[24]; 74 s.Seek(peSignatureOffset, SeekOrigin.Begin); 75 s.Read(coffHeader, 0, 24); 76 byte[] signature = { (byte)'P', (byte)'E', (byte)'