Link to home
Start Free TrialLog in
Avatar of vmaxx
vmaxx

asked on

Map network drive {WNetAddConnection}

I am trying to write a program that will map net work drives on Nt W/S 4.0 sp5 using VB4. I am using the WNetAddConnection call - some times it works, some times it gives me error 1326 or 1909. Right after it gives me the error I can go to Nt Explorer and map the exact network drive I just tried with no problem. I have tried using an administrative password in the call with no luck. On some machines some drives work fine and other drives fail.
Avatar of Ruchi
Ruchi

From the web:

"The Netware connection will connect as the current user, the NT code requires a username and password. For my purposes I set the code to login as administrator, but you could easily change this to any user, or even prompt the user for username and password prior to mapping a drive. "

The following code is in the class module.


Option Explicit

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

    Private Declare Function WNetCancelConnection Lib "mpr.dll" Alias "WNetCancelConnectionA" _
            (ByVal lpszName As String, _
             ByVal bForce As Long) As Long
         
'declare NT APIs
    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
   
'NetWare Vars
    Const NW_Success = &H0
    Const NW_Not_Supported = &H1
    Const NW_Net_Error = &H2
    Const NW_Bad_Pointer = &H4
    Const NW_Bad_NetName = &H32
    Const NW_Bad_Password = &H6
    Const NW_Bad_Localname = &H33
    Const NW_Access_Denied = &H7
    Const NW_Out_Of_Memory = &HB
    Const NW_Already_Connected = &H34

    Private Const ERROR_NO_CONNECTION = 8
    Private Const ERROR_NO_DISCONNECT = 9

    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
       
'NT Vars
    Const NO_ERROR = 0
    Const CONNECT_UPDATE_PROFILE = &H1
    Const RESOURCETYPE_DISK = &H1
    Const RESOURCETYPE_PRINT = &H2
    Const RESOURCETYPE_ANY = &H0
    Const RESOURCE_CONNECTED = &H1
    Const RESOURCE_REMEMBERED = &H3
    Const RESOURCE_GLOBALNET = &H2
    Const RESOURCEDISPLAYTYPE_DOMAIN = &H1
    Const RESOURCEDISPLAYTYPE_GENERIC = &H0
    Const RESOURCEDISPLAYTYPE_SERVER = &H2
    Const RESOURCEDISPLAYTYPE_SHARE = &H3
    Const RESOURCEUSAGE_CONNECTABLE = &H1
    Const RESOURCEUSAGE_CONTAINER = &H2
   
    Dim RC As Long

'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
''   Sub to Disconnect mapped drive
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''
''   Error Codes:
''       2250    - not disconnected for (some reason)
''
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function Disconnect(Drive As String) As Long

    'attempt to disconnect NT type connection
        Disconnect = WNetCancelConnection2(Drive, CONNECT_UPDATE_PROFILE, False)
   
    'if not worked, attempt to disconnect NetWare type connection
        If Disconnect <> 0 Then _
            Disconnect = WNetCancelConnection(Drive + Chr(0), 0)
End Function

   
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'   Sub to Map network drive
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'
'   Error Codes:
'       0    - Connected
'       67   - bad UNC
'       85   - not connected due to existing connection on specified drive letter
'       1202 - attempt to connect NT on existing NW mapping OR
'            - attempt to connect NW on existing NT mapping
'       1219 - server valid, path invalid
'       1326 - invalid username/password OR attempt to connect NT with NW code
'       2202 - ?
'
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
   
Public Function Connect(Drive As String, UNC As String) As Long
    Dim Disconnected As Long
    Dim Answer
   
    Dim NetR As NETRESOURCE         'for mapping

    NetR.dwScope = RESOURCE_GLOBALNET
    NetR.dwType = RESOURCETYPE_DISK
    NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
    NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE
    NetR.lpLocalName = Drive
    NetR.lpRemoteName = UNC

ConnectNW:
    'attempt Netware type connection
    Connect = WNetAddConnection(UNC & Chr(0), "" & Chr(0), Drive & Chr(0))

    If Connect = 0 Then
        Exit Function
        ElseIf Connect = 85 Then
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNW

            Answer = MsgBox("Could not map a drive to " & UNC & " due to the " & _
                            "drive letter already being in use." & vbLf & _
                            "Please disconnect the I: drive and try again", _
                             vbRetryCancel + vbCritical, "Error Attempting " & _
                            "to Connect to " & UNC)
            If Answer = vbRetry Then GoTo ConnectNW
       
        ElseIf Connect = 1202 Then
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNW
        End If
   
ConnectNT:
    'attempt NT type connection if Netware connection fails
    Connect = WNetAddConnection2(NetR, "password", "user name", CONNECT_UPDATE_PROFILE)
   
    If Connect = 0 Then
        Exit Function
        ElseIf Connect = 67 Then
            MsgBox UNC & " is either invalid or unavailable!" & vbLf & vbLf & _
                   "Program execution may be affected by this situation", vbCritical, "" & _
                   "Error connecting to " & UNC
            Exit Function
       
        ElseIf Connect = 85 Then
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNT

            Answer = MsgBox("Could not map a drive to " & UNC & " due to the " & _
                            "drive letter already being in use." & vbLf & _
                            "Please disconnect the I: drive and try again", _
                             vbRetryCancel + vbCritical, "Error Attempting " & _
                            "to Connect to " & UNC)
            If Answer = vbRetry Then GoTo ConnectNT
       
        ElseIf Connect = 1202 Then
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNT
           
        ElseIf Connect = 1326 Then
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNT
            Answer = MsgBox("Class NETUSE is hard coded to login as Administrator.  " & _
                            "The error code returned indicates that the Username/" & _
                            "Password" & vbLf & "is incorrect. Most probable cause " & _
                            "is that the Administrator password has been changed", _
                             vbRetryCancel + vbCritical, "Error Attempting to " & _
                            "Connect to " & UNC)
            If Answer = vbRetry Then GoTo ConnectNT
       
        Else
            Disconnected = Disconnect(Drive)
            If Disconnected = 0 Then GoTo ConnectNT
            MsgBox "A critical and Unknown error has occured while trying to attach " & _
                   "to " & UNC & vbLf & vbLf & "The Error Code was: " & _
                    Connect & vbLf & vbLf & "Program execution my be affected by " & _
                   "this situation", vbCritical
            Exit Function
       
        End If
   

End Function

Check the password and login time
Avatar of vmaxx

ASKER

There should be no password - what is the login time? Is it like a timeout value - how is it set.
I see there is a WNetAddConnection2 - is that any different and what are its parameters.
Avatar of vmaxx

ASKER

Ruchi - I pasted your code into a class module - then tried calling it from a form by "connect(drive, unc)" but it errors out. Am I forgetting something?
I will work with the first code I gave you from the web by tonight or tomorrow. But, I give you another code that is to map a network drive.

Option Explicit

Private Const CONNECT_UPDATE_PROFILE = &H1

Private Const RESOURCE_CONNECTED As Long = &H1&
Private Const RESOURCE_GLOBALNET As Long = &H2&
Private Const RESOURCETYPE_DISK As Long = &H1&
Private Const RESOURCEDISPLAYTYPE_SHARE& = &H3
Private Const RESOURCEUSAGE_CONNECTABLE As Long = &H1&

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

Private Type NETCONNECT
 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

Code:

Public Function MapDrive(LocalDrive As String, _
RemoteDrive As String, Optional Username As String, _
Optional Password As String) As Boolean

'Example:
'MapDrive "Q:", "\\RemoteMachine\RemoteDirectory", _
'"MyLoginName", "MyPassword"

 Dim NetR As NETCONNECT

 NetR.dwScope = RESOURCE_GLOBALNET
 NetR.dwType = RESOURCETYPE_DISK
 NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
 NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE
 NetR.lpLocalName = Left$(LocalDrive, 1) & ":"
 NetR.lpRemoteName = RemoteDrive

 MapDrive = (WNetAddConnection2(NetR, Username, Password, _
     CONNECT_UPDATE_PROFILE) = 0)
 

End Function

Avatar of vmaxx

ASKER

I really appriciate the time, I have wanted to complete this for off and on two years now. You get this working and name your price.
Did you get it working?
Name your price?? Thanks for your offer. But, I don't want any money or anything. Please let me know if you get it working or not.
Avatar of vmaxx

ASKER

No, I try different procedures in modules, forms, class modules - and each time different errors pop up, never actually gets to the mapping part of it to see if that part works.
try taking a look at...

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=1&txtCodeId=196

I am in a hurry now, but please tell me about that site. if it's not good enough to you, I will work tomorrow with the  first code I gave.
ASKER CERTIFIED SOLUTION
Avatar of freelnce
freelnce

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of vmaxx

ASKER

The code from the URL partially works, what ever the first drive to be mapped always works, but when I try to map additional drives to different UNC paths, it never works. It dosen't matter what the first drive I try, it works, but subsequent drives fail. I step through the code - it dosen't error out, but the line that actually mapps the drive gets ran, but dosen't map the drive. I checked the parameters on the second drive to be mapped and the parameters are changed for the new drive. I tried using API monitor on it, but there are jsut too many things going on for me to make sense of.
It almost seems that some thing is not getting released after the first mapping. I cannot rule out something funky going on with my LAN, it has been online for a long time.
One other thing, when it does connect the first drive - it makes the connection reconnect the next time a user logs in.
Avatar of vmaxx

ASKER

The code from the URL partially works, what ever the first drive to be mapped always works, but when I try to map additional drives to different UNC paths, it never works. It dosen't matter what the first drive I try, it works, but subsequent drives fail. I step through the code - it dosen't error out, but the line that actually mapps the drive gets ran, but dosen't map the drive. I checked the parameters on the second drive to be mapped and the parameters are changed for the new drive. I tried using API monitor on it, but there are jsut too many things going on for me to make sense of.
It almost seems that some thing is not getting released after the first mapping. I cannot rule out something funky going on with my LAN, it has been online for a long time.
One other thing, when it does connect the first drive - it makes the connection reconnect the next time a user logs in.
Kind of in a hurry.....
Get this code from the web

Option Explicit

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

Const NO_ERROR = 0
Const CONNECT_UPDATE_PROFILE = &H1
Const RESOURCETYPE_DISK = &H1
Const RESOURCETYPE_PRINT = &H2
Const RESOURCETYPE_ANY = &H0
Const RESOURCE_CONNECTED = &H1
Const RESOURCE_REMEMBERED = &H3
Const RESOURCE_GLOBALNET = &H2
Const RESOURCEDISPLAYTYPE_DOMAIN = &H1
Const RESOURCEDISPLAYTYPE_GENERIC = &H0
Const RESOURCEDISPLAYTYPE_SERVER = &H2
Const RESOURCEDISPLAYTYPE_SHARE = &H3
Const RESOURCEUSAGE_CONNECTABLE = &H1
Const RESOURCEUSAGE_CONTAINER = &H2

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 Sub cmdConnect_Click()

Dim NetR As NETRESOURCE
Dim ErrInfo As Long

NetR.dwScope = RESOURCE_GLOBALNET
NetR.dwType = RESOURCETYPE_DISK
NetR.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE
NetR.dwUsage = RESOURCEUSAGE_CONNECTABLE
NetR.lpLocalName = Text1(0).Text
NetR.lpRemoteName = Text1(1).Text

ErrInfo = WNetAddConnection2(NetR, Text1(3).Text, Text1(2).Text, CONNECT_UPDATE_PROFILE)

If ErrInfo = NO_ERROR Then
    MsgBox "Net connection successful!", vbInformation
Else
    MsgBox "ERROR: " & Str(ErrInfo) & " - Net connection unsuccessful!", _
    vbExclamation
End If

End Sub

Private Sub cmdDisconnect_Click()

Dim ErrInfo As Long
Dim strLocalName As String

strLocalName = Text1(4).Text
ErrInfo = WNetCancelConnection2(strLocalName, CONNECT_UPDATE_PROFILE, False)

If ErrInfo = NO_ERROR Then
    MsgBox "Net disconnection successful!", vbInformation
Else
    MsgBox "ERROR: " & Str(ErrInfo) & " - Net disconnection unsuccessful!", _
    vbExclamation
End If

End Sub

Vmaxx: Where are you? Please say something so we could be of any help to you.
Avatar of vmaxx

ASKER

Sorry about that, still trying to get the parameters of the call right from your last post.

What are the parameters of the controlled text box:
NetR.lpLocalName=Text1(0).text
NetR.lpRemoteName=Text1(1).text

WNetAddConnection2(NetR, Text1(3).text, Text1((2).text, CONNECT_UPDATE_PROFILE)

What values are going to be in the text boxes. I have tried the Local drive name and UNC path, but get: Error 2202 Net Connection Unsuccessful..

What I want it for will have fixed values for the drives so variable objects like text boxes will not be needed.
Glad that it worked for you! And, I'm glad that Freelnce helped you!
Avatar of vmaxx

ASKER

I am unfamiliar with that API call, do you know how to use the NetResourse type of the call:
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 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

Also the Flags portion of the call - what info does that hold.
I really cannot explain to you in my word how to use the NetResource type of the call. But, I found that information from the web.

From http://www.mvps.org/vbnet/code/network/netconnect.htm :

Allows the caller to redirect (connect) a local device to a network resource. It is similar to
WNetAddConnection, except that it takes a pointer to a NETRESOURCE structure to describe the network
resource to connect to. It also takes the addition parameters lpUserID and dwFlags.

lpNetResource -------------------
Specifies the network resource to connect to. The following fields must be set when making a
connection, the others are ignored.

lpRemoteName----------------------
Specifies the network resource to connect to. This is limited to MAX_PATH.

lpLocalName--------------------
This specifies the name of a local device to be redirected, such as "F:"
or "LPT1". The string is treated in a case insensitive manner, and may be
the empty string (or NULL) in which case a connection to the network resource
is made without making a redirection.

lpProvider--------------------
Specifies the NP to connect to. If NULL or empty string, Windows will try each
NP in turn. The caller should set lpProvider only if it knows for sure
which network it wants. Otherwise, it is preferable to let Windows determine
which NP the network name maps to. If this is non NULL, Windows will try
the named NP and no other.

dwType-------------------
Specifies the type of resource to connect to. It must be RESOURCETYPE_DISK or RESOURCETYPE_PRINT
if lpLocalName is not the empty string. It may also be RESOURCETYPE_ANY if lpLocalName is the
empty string.

lpPassword---------------
Specifies the password to be used in making the connection, normally the password associated with
lpUserID. A NULL value or string may be passed in to indicate to the function to use the
current 'default password.'

lpUserID------------------
This specifies the identity of the user needed to make the connection. If NULL, a default will be
applied. This is used when the user wishes to connect to a resource, but has a different user name or
account assigned to him for that resource. This identification represents a security
context, and'is NP specific.

----------------------------------

Here a few web sites regarding the mapped network drive

http://support.microsoft.com/support/kb/articles/Q177/6/97.asp

http://support.microsoft.com/support/kb/articles/Q173/0/11.asp

http://support.microsoft.com/support/kb/articles/Q177/6/98.asp

http://support.microsoft.com/support/kb/articles/Q192/6/89.asp

http://www.mwe.8m.com/vb/tips/tip7.htm

http://www.inquiry.com/techtips/thevbpro/10_minute_solutions/10min0799.asp

http://vbarchives.hypermart.net/tiparchive/internet/Internet005.htm

http://www.vbsquare.com/misc/tip350.html




Hope this helps you!!!
Thanks.
Vmaxx: Does it help you a lot? Please let me know.
Thanks.
Avatar of vmaxx

ASKER

Actually yes, please post something as an answer so I can award you the points. I have not gone through all the articles, but am happy with what I got so far.
Thanks for all the help and effort.
Vmaxx:
Well, I cannot post this as an answer because you accepted freelnce's answer. You can post a new question or you can ignore this. Whatever you choose is perfectly fine with me. I am extremely glad that I could be of any help to you ;-)
All the best.