C#获取ADSL所有宽带连接名称

1.通过注册表获取,缺点,兼容性差

1 //RegistryKey userKey = Registry.CurrentUser;
2 //RegistryKey key = userKey.OpenSubKey(@"RemoteAccess\Profile");
3 //string[] keysList = key.GetSubKeyNames();//获取当前创建的adsl宽带列表


2.通过api获取,兼容性比上面好

#region 获取adsl所有宽带连接名称

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RasEntryName      //define the struct to receive the entry name
{
    public int dwSize;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256 + 1)]
    public string szEntryName;
    #if WINVER5
     public int dwFlags;
     [MarshalAs(UnmanagedType.ByValTStr,SizeConst=260+1)]
     public string szPhonebookPath;
    #endif
}

[DllImport("rasapi32.dll", CharSet = CharSet.Auto)]

public extern static uint RasEnumEntries(
    string reserved,              // reserved, must be NULL
    string lpszPhonebook,         // pointer to full path and file name of phone-book file
    [In, Out]RasEntryName[] lprasentryname, // buffer to receive phone-book entries
    ref int lpcb,                  // size in bytes of buffer
    out int lpcEntries             // number of entries written to buffer
);

public static List<string> GetAllAdslName()
{
    List<string> list = new List<string>();
    int lpNames = 1;
    int entryNameSize = 0;
    int lpSize = 0;
    RasEntryName[] names = null;
    entryNameSize = Marshal.SizeOf(typeof(RasEntryName));
    lpSize = lpNames * entryNameSize;
    names = new RasEntryName[lpNames];
    names[0].dwSize = entryNameSize;
    uint retval = RasEnumEntries(null, null, names, ref lpSize, out lpNames);

    //if we have more than one connection, we need to do it again
    if (lpNames > 1)
    {
        names = new RasEntryName[lpNames];
        for (int i = 0; i < names.Length; i++)
        {
            names[i].dwSize = entryNameSize;
        }
        retval = RasEnumEntries(null, null, names, ref lpSize, out lpNames);
    }

    if (lpNames > 0)
    {
        for (int i = 0; i < names.Length; i++)
        {
            list.Add(names[i].szEntryName);
        }
    }
    return list;
}

#endregion
posted @ 2011-07-29 20:41  事理  阅读(2353)  评论(0编辑  收藏  举报