You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

RAS.cs 2.9 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Text;
  6. namespace Shadowsocks.WPF.Services.SystemProxy
  7. {
  8. public enum RasFieldSizeConst
  9. {
  10. MaxEntryName = 256,
  11. MaxPath = 260,
  12. }
  13. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  14. public struct RasEntryName
  15. {
  16. public int dwSize;
  17. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS.MaxEntryName + 1)]
  18. public string szEntryName;
  19. public int dwFlags;
  20. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS.MaxPath + 1)]
  21. public string szPhonebookPath;
  22. }
  23. public class RAS
  24. {
  25. public const int MaxEntryName = 256;
  26. public const int MaxPath = 260;
  27. const int ESuccess = 0;
  28. const int RasBase = 600;
  29. const int EBufferTooSmall = 603;
  30. [DllImport("rasapi32.dll", CharSet = CharSet.Auto)]
  31. private static extern uint RasEnumEntries(
  32. // reserved, must be NULL
  33. string reserved,
  34. // pointer to full path and file name of phone-book file
  35. string lpszPhonebook,
  36. // buffer to receive phone-book entries
  37. [In, Out] RasEntryName[]? lprasentryname,
  38. // size in bytes of buffer
  39. ref int lpcb,
  40. // number of entries written to buffer
  41. out int lpcEntries
  42. );
  43. public static string[] GetAllConnections()
  44. {
  45. int lpNames = 0;
  46. int entryNameSize = 0;
  47. int lpSize = 0;
  48. uint retval = ESuccess;
  49. RasEntryName[] names = Array.Empty<RasEntryName>();
  50. entryNameSize = Marshal.SizeOf(typeof(RasEntryName));
  51. // Windows Vista or later: To determine the required buffer size, call RasEnumEntries
  52. // with lprasentryname set to NULL. The variable pointed to by lpcb should be set to zero.
  53. // The function will return the required buffer size in lpcb and an error code of ERROR_BUFFER_TOO_SMALL.
  54. retval = RasEnumEntries("", "", null, ref lpSize, out lpNames);
  55. if (retval == EBufferTooSmall)
  56. {
  57. names = new RasEntryName[lpNames];
  58. for (int i = 0; i < names.Length; i++)
  59. {
  60. names[i].dwSize = entryNameSize;
  61. }
  62. retval = RasEnumEntries("", "", names, ref lpSize, out lpNames);
  63. }
  64. if (retval == ESuccess)
  65. {
  66. if (lpNames == 0)
  67. {
  68. // no entries found.
  69. return Array.Empty<string>();
  70. }
  71. return names.Select(n => n.szEntryName).ToArray();
  72. }
  73. else
  74. {
  75. throw new Exception();
  76. }
  77. }
  78. }
  79. }