February 19, 2019
Hot Topics:

Adding a Network Connection to Your Computer

  • November 20, 2002
  • By Steve Anderson
  • Send Email »
  • More Articles »

Adding a network connection can be easily done by using map network drive in Network Neighborhood or My Computer, but it can be useful to be able to do this in Visual Basic. In this example you will learn how to create the connection using the Windows API and how to delete a connection as well.

  • Start a new Standard-EXE project, form1 is created by default
  • Add a standard module and add a command button to form1
  • Type the following in the standard module.
Option Explicit

Declare Function _
WNetAddConnection Lib _
"mpr.dll" Alias _
"WNetAddConnectionA" _
(ByVal lpszNetPath As String, _
ByVal lpszPassword As String, _
 ByVal lpszLocalName _
As String) As Long

Declare Function _
WNetCancelConnection _
Lib "mpr.dll" _
Alias "WNetCancelConnectionA _
" (ByVal lpszName _
As String, ByVal bForce As Long)_
As Long

Const WN_SUCCESS = 0 ' _
The function was successful.
Const WN_NET_ERROR = 2 ' _
An error occurred on the network.
Const WN_BAD_PASSWORD = 6 ' _
The password was invalid.

Function AddConnection _
(MyShareName As String, _
MyPWD As String, UseLetter _
As String) As Integer

On Local Error GoTo _

AddConnection = _
WNetAddConnection(MyShareName, _
MyPWD, UseLetter)

Exit Function

AddConnection = Err
MsgBox Error$

Resume AddConnection_End

End Function

Function CancelConnection _
(DriveLetter As String, _
Force As Integer) As Integer

On Local Error GoTo _
CancelConnection = _
WNetCancelConnection(DriveLetter, _

Exit Function

CancelConnection = Err
MsgBox Error$

Resume CancelConnection_End

End Function
  • to add a connection call by:
varible = AddConnection _
(<SharePath>, _
<Password>, _
  • To cancel a connection type:
varible = CancelConnection _
(<SharePath, <Force>)

Run the project.

Comment and Contribute


(Maximum characters: 1200). You have characters left.



Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date