Cómo conectarse a una unidad de red

Publicado: 23/Jun/99


Este es un ejemplo de cómo conectarse y desconectarse de unidades de red, usando código de Visual Basic... con ayuda del API de Windows.
El código aquí mostrado está sacado de la Knowledge Base de Microsoft, artículo Q173011. Lo que yo he hecho ha sido probarlo y adaptarlo para su uso en un formulario... pero como creo que es un tema que a más de uno le puede interesar... aquí está.
He dejado los comentarios originales... en inglés, claro.

Puedes bajarte el código de ejemplo, (net.zip 2.67 KB) aunque básicamente es muy simple, lo que al formulario se refiere, ya que el código a usar es el que te muestro a continuación.

Este es el aspecto del formulario en ejecución:

'------------------------------------------------------------------------------
' Prueba de conexión / desconexión a unidades de red                (23/Jun/99)
'
' ©Guillermo 'guille' Som, 1999
'
' Ejemplo basado en un artículo de la Knowledge Base de Microsoft:
'   HOWTO: Add and Remove Network Connections
'   Article ID: Q173011
'------------------------------------------------------------------------------
Option Explicit

Private Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" _
    (lpNetResource As NETRESOURCE, ByVal lpPassword As String, _
    ByVal lpUserName As String, ByVal dwFlags As Long) As Long

Private Declare Function WNetCancelConnection2 Lib "mpr.dll" Alias "WNetCancelConnection2A" _
    (ByVal lpName As String, ByVal dwFlags As Long, ByVal fForce As Long) As Long

Private Type NETRESOURCE
    dwScope As Long
    dwType As Long
    dwDisplayType As Long
    dwUsage As Long
    lpLocalName As String
    lpRemoteName As String
    lpComment As String
    lpProvider As String
End Type

Private Const NO_ERROR = 0
Private Const CONNECT_UPDATE_PROFILE = &H1
' The following includes all the constants defined for NETRESOURCE,
' not just the ones used in this example.
Private Const RESOURCETYPE_DISK = &H1
Private Const RESOURCETYPE_PRINT = &H2
Private Const RESOURCETYPE_ANY = &H0
Private Const RESOURCE_CONNECTED = &H1
Private Const RESOURCE_REMEMBERED = &H3
Private Const RESOURCE_GLOBALNET = &H2
Private Const RESOURCEDISPLAYTYPE_DOMAIN = &H1
Private Const RESOURCEDISPLAYTYPE_GENERIC = &H0
Private Const RESOURCEDISPLAYTYPE_SERVER = &H2
Private Const RESOURCEDISPLAYTYPE_SHARE = &H3
Private Const RESOURCEUSAGE_CONNECTABLE = &H1
Private Const RESOURCEUSAGE_CONTAINER = &H2
' Error Constants:
Private Const ERROR_ACCESS_DENIED = 5&
Private Const ERROR_ALREADY_ASSIGNED = 85&
Private Const ERROR_BAD_DEV_TYPE = 66&
Private Const ERROR_BAD_DEVICE = 1200&
Private Const ERROR_BAD_NET_NAME = 67&
Private Const ERROR_BAD_PROFILE = 1206&
Private Const ERROR_BAD_PROVIDER = 1204&
Private Const ERROR_BUSY = 170&
Private Const ERROR_CANCELLED = 1223&
Private Const ERROR_CANNOT_OPEN_PROFILE = 1205&
Private Const ERROR_DEVICE_ALREADY_REMEMBERED = 1202&
Private Const ERROR_EXTENDED_ERROR = 1208&
Private Const ERROR_INVALID_PASSWORD = 86&
Private Const ERROR_NO_NET_OR_BAD_PATH = 1203&


Private Sub cmdAdd_Click()
    Dim NetR As NETRESOURCE
    Dim ErrInfo As Long
    ' Datos del usuario y password
    Dim MyPass As String, MyUser As String
    Dim sPath As String
    
    sPath = CurDir$
    
    NetR.dwScope = RESOURCE_GLOBALNET
    NetR.dwType = RESOURCETYPE_DISK
    NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
    NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE
    NetR.lpLocalName = txtLocal ' If undefined, Connect with no device
    NetR.lpRemoteName = txtNet  ' Your valid share
    'NetR.lpComment = "Optional Comment"
    'NetR.lpProvider =    ' Leave this undefined
    
    ' If the UserName and Password arguments are NULL, the user context
    ' for the process provides the default user name.
    ErrInfo = WNetAddConnection2(NetR, MyPass, MyUser, CONNECT_UPDATE_PROFILE)
    If ErrInfo = NO_ERROR Then
        lblStatus = " Conexión realizada con éxito"
        sPath = txtLocal
    Else
        lblStatus = " ERROR al intentar realizar la conexión"
        MsgBox "ERROR: " & ErrInfo & " - Net Connection Failed!", vbExclamation, "Share not Connected"
    End If
    
    ' Rellenar el DirBox
    Dir1.Path = sPath
End Sub


Private Sub cmdCancel_Click()
    Dim ErrInfo As Long
    Dim strLocalName As String
    
    ' You may specify either the lpRemoteName or lpLocalName
    'strLocalName = "\\ServerName\ShareName"
    strLocalName = txtLocal
    ErrInfo = WNetCancelConnection2(strLocalName, CONNECT_UPDATE_PROFILE, False)
    If ErrInfo = NO_ERROR Then
        lblStatus = " Desconectado de la unidad " & strLocalName & " satisfactoriamente"
    Else
        lblStatus = " ERROR al desconectar la unidad " & strLocalName
        MsgBox "ERROR: " & ErrInfo & " - Net Disconnection Failed!", vbExclamation, "Share not Disconnected"
    End If
    
    Dir1.Path = CurDir$
End Sub


ir al índice