SystemHelper.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. namespace NetFilterHelper.Utils
  8. {
  9. public class SystemHelper
  10. {
  11. /// <summary>
  12. /// The function determines whether the current operating system is a
  13. /// 64-bit operating system.
  14. /// </summary>
  15. /// <returns>
  16. /// The function returns true if the operating system is 64-bit;
  17. /// otherwise, it returns false.
  18. /// </returns>
  19. public static bool Is64BitOperatingSystem()
  20. {
  21. if (IntPtr.Size == 8) // 64-bit programs run only on Win64
  22. {
  23. return true;
  24. }
  25. else // 32-bit programs run on both 32-bit and 64-bit Windows
  26. {
  27. // Detect whether the current process is a 32-bit process
  28. // running on a 64-bit system.
  29. bool flag;
  30. return ((DoesWin32MethodExist("kernel32.dll", "IsWow64Process") &&
  31. IsWow64Process(GetCurrentProcess(), out flag)) && flag);
  32. }
  33. }
  34. /// <summary>
  35. /// The function determins whether a method exists in the export
  36. /// table of a certain module.
  37. /// </summary>
  38. /// <param name="moduleName">The name of the module</param>
  39. /// <param name="methodName">The name of the method</param>
  40. /// <returns>
  41. /// The function returns true if the method specified by methodName
  42. /// exists in the export table of the module specified by moduleName.
  43. /// </returns>
  44. static bool DoesWin32MethodExist(string moduleName, string methodName)
  45. {
  46. IntPtr moduleHandle = GetModuleHandle(moduleName);
  47. if (moduleHandle == IntPtr.Zero)
  48. {
  49. return false;
  50. }
  51. return (GetProcAddress(moduleHandle, methodName) != IntPtr.Zero);
  52. }
  53. [DllImport("kernel32.dll")]
  54. static extern IntPtr GetCurrentProcess();
  55. [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  56. static extern IntPtr GetModuleHandle(string moduleName);
  57. [DllImport("kernel32", CharSet = CharSet.Auto, SetLastError = true)]
  58. static extern IntPtr GetProcAddress(IntPtr hModule,
  59. [MarshalAs(UnmanagedType.LPStr)] string procName);
  60. [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  61. [return: MarshalAs(UnmanagedType.Bool)]
  62. static extern bool IsWow64Process(IntPtr hProcess, out bool wow64Process);
  63. [DllImport("kernel32.dll", SetLastError = true)]
  64. public static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);
  65. [DllImport("kernel32.dll", SetLastError = true)]
  66. public static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);
  67. }
  68. }