How to delete VPN connection (.pbk) in DotRas C#?

707 Views Asked by At

When my VPN client connects to my VPN server, it creates a .PBK connection, but when i trying to create another connection with another IP, it throws me

System.ArgumentException: 'ConnectionName' already exists in the phone book.

I know i can create different connection name each time i trying to connect, but over time there will be too much unnecessary connections, how can i remove my connection via DotRas or manually?

This folder is totally clear. Don't know what to do.

%AppData%\Roaming\Microsoft\Network\Connections\Pbk
2

There are 2 best solutions below

0
On

A RasCollection, which is what RasPhoneBook.Entries is, provides several methods that can be used. In the end, it is an ICollection/IEnumerable.

...
public abstract class RasCollection<TObject> : MarshalByRefObject, ICollection<TObject>, IEnumerable<TObject>, IEnumerable where TObject : class
{
    ...

    public int Count { get; }
    ...

    public void Add(TObject item);
    public void Clear();
    public bool Contains(TObject item);
    ...
    ...
    public int IndexOf(TObject item);
    public bool Remove(TObject item);
    public void RemoveAt(int index);
    ...
}

To remove items, one can use Remove() given a RasEntry, RemoveAt() given an index, or Clear() to remove everything.

Additionally, RasEntryCollection provides public bool Remove(string name) which one can use to remove an entry given its name.

Source: I needed to create a VPN software recently. Lack of documentation did not help.

0
On

Found an answer to my question. If you declare your entry like this:

RasEntry entry = RasEntry.CreateVpnEntry(EntryName, ip, RasVpnStrategy.Default,
RasDevice.GetDeviceByName("(PPTP)", RasDeviceType.Vpn));

You need to use Remove() method:

this.AllUsersPhoneBook.Entries.Remove(Entry);