Attempt to connect to network share with wnetaddconnection2 fails error 1326

I am trying to connect to a network resource using WNETaddconnection2. The function keeps returning error 1326 which is LOGON FAILURE, when I try to connect to \\COMPUTER\SHARE.  I am using VB .NET 2003.

I can run NET USE \\COMPUTER\SHARE /USER:myuname  from the command line and it succeeds.  The default user name and password combination (myuname, mypass) is a valid user on the network resource.  

Following is all of the declarations and code that I used.  In the procedure, CONNECT_SH(), the variable DBPATH a string and is set to "\\COMPUTER\SHARE" .  The user name is pulled from windows using the GETUSERNAME API and I can see that is set to myuname when I am debugging.    

<StructLayout(LayoutKind.Sequential)> _
    Public Structure NetResource
        Public Scope As Integer
        Public dType As Integer
        Public dDispType As Integer
        Public dUsage As Integer
        <MarshalAs(UnmanagedType.LPTStr)> _
        Public localname As String
        <MarshalAs(UnmanagedType.LPTStr)> _
        Public remotename As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=50)> _
        Public comment As String
        <MarshalAs(UnmanagedType.ByValTStr, SizeConst:=10)> _
       Public provider As String
    End Structure

    Public Const NO_ERROR As Integer = 0
    Public Const CONNECT_LOCALDRIVE As Integer = 256
    Public Const CONNECT_REDIRECT As Integer = 128
    Public Const RESOURCE_CONNECTED As Integer = &H1
    Public Const RESOURCE_GLOBALNET As Integer = &H2
    Public Const RESOURCE_REMEMBERED As Integer = &H3
    Public Const RESOURCETYPE_ANY As Integer = &H0
    Public Const RESOURCETYPE_DISK As Integer = &H1
    Public Const RESOURCETYPE_PRINT As Integer = &H2
    Public Const RESOURCEDISPLAYTYPE_DOMAIN As Integer = &H1
    Public Const RESOURCEDISPLAYTYPE_SERVER As Integer = &H2
    Public Const RESOURCEDISPLAYTYPE_SHARE As Integer = &H3
    Public Const RESOURCEDISPLAYTYPE_FILE As Integer = &H4
    Public Const RESOURCEDISPLAYTYPE_GROUP As Integer = &H5

    Public Const RESOURCEUSAGE_CONNECTABLE As Integer = &H1
    Public Const RESOURCEUSAGE_CONTAINER As Integer = &H2
    Public Const CONNECT_UPDATE_PROFILE As Integer = 1

  Public Declare Auto Function WNetAddConnection2 Lib "mpr.dll" _
       Alias "WNetAddConnection2" (ByRef lpNetResource As NetResource, _
                                    ByVal lpPassword As String, _
                                    ByVal lpUsername As String, _
                                    ByVal dwFlags As Integer) As Integer

    Public Declare Function GetUserName Lib "advapi32.dll" Alias _
         "GetUserNameA" (ByVal lpbuffer As String, _
                         ByRef nsize As Integer) As Integer

  Public Function ConnectSh() As Boolean

        Dim x, lans As Integer
        Dim lclu, lclp, dsource As String
        Dim ldate As Date
        Dim netrs As Win32API.NetResource
      Dim nullstr, lpw, lun, utemp As String
        nullstr = Chr(0)

        netrs.localname = nullstr
        netrs.provider = nullstr
        netrs.remotename = dbpath + Chr(0)
        netrs.comment = nullstr
        netrs.dType = Win32API.RESOURCETYPE_DISK
      '  netrs.Scope = Win32API.RESOURCE_GLOBALNET
      netrs.Scope = 0

         utemp = New String(CChar(" "), 50)
         lans = Win32API.GetUserName(utemp, 50)
         lun = utemp
         lpw = ""
      lans = Win32API.WNetAddConnection2(netrs, lpw, lun, 0)
      If lans = 0 Then
         Return True
         Return False
      End If
    End Function

I have tried numerous variations of the code

   1. Setting lun to "myuname"

   2. Setting lun to "myuname" + nullstr

   3. Setting lpw to nullstr (With each of the combinations above)

Again I can go to the command line and type

   NET USE \\COMPUTER\SHARE /USER:myuname  and it connects to the resource.

Any ideas???????????


Who is Participating?
nffvrxqgrcfqvvcConnect With a Mentor Commented:
BTW: I noticed your using "" which might cause the function to fail. Use the example in the code block.
' Correct way to call this method.
WNet.AddConnection("user", Nothing, "\\\shared", Nothing)

Open in new window

Try using something like this..

Imports System.Runtime.InteropServices
Imports System.ComponentModel

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
            WNet.AddConnection("user", "password", "\\\share", "r:\")
            Debug.Print("AddConnection - Success")
        Catch ex As Win32Exception
            Debug.Print("code={0} message={1}", ex.ErrorCode, ex.Message)
        End Try

    End Sub
End Class

Public Class WNet
    Private Const NO_ERROR As Integer = 0

    Private Enum WNetType As Integer
    End Enum

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Unicode)> _
    Public Structure NETRESOURCE
        Dim dwScope As Integer
        Dim dwType As Integer
        Dim dwDisplayType As Integer
        Dim dwUsage As Integer
        Dim lpLocalName As String
        Dim lpRemoteName As String
        Dim lpComment As String
        Dim lpProvider As String
    End Structure

    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function WNetAddConnection2(ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUsername As String, ByVal dwFlags As Integer) As Integer
    End Function

    <DllImport("mpr.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function WNetCancelConnection2(ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
    End Function

    Private Shared _pRemote As String = String.Empty
    Private Shared _pLocal As String = String.Empty

    Public Shared Sub AddConnection(ByVal userName As String, ByVal password As String, ByVal remoteName As String, ByVal localName As String)

        Dim nr As NETRESOURCE = Nothing
        Dim dwResult As Integer = NO_ERROR

        _pLocal = localName
        _pRemote = remoteName

        nr.lpRemoteName = remoteName
        nr.lpLocalName = localName
        nr.dwType = WNetType.RESOURCETYPE_ANY

        dwResult = WNetAddConnection2(nr, password, userName, 0)

        If dwResult <> NO_ERROR Then
            Throw New Win32Exception(Marshal.GetLastWin32Error)
        End If

    End Sub

    Public Shared Sub CancelConnection(ByVal szName As String)
        Dim dwResult As Integer = NO_ERROR

        dwResult = WNetCancelConnection2(szName, 0, 1)

        If dwResult <> NO_ERROR Then
            Throw New Win32Exception(Marshal.GetLastWin32Error)
        End If

    End Sub

    Public Shared ReadOnly Property LocalName() As String
            Return _pLocal
        End Get
    End Property

    Public Shared ReadOnly Property RemoteName() As String
            Return _pRemote
        End Get
    End Property

End Class

Open in new window

My bad.. There shouldn't be a trailing backslash in the example. (See code section)
WNet.AddConnection("username", "password", "\\\share", "R:")

Open in new window

Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

knk53Author Commented:
   That responded with the same error.  1326.   How should I call the function if I want to use the default user name and password?   Also, I dont want a drive letter just the resource.    
If you don't want a drive letter you dont have to specify the local name (see code section)
There is a couple of things you will want to make sure that your credentials are correct. It wouldn't hurt either to go to the computer that is hosting the share and remove it then re-enable. Then try again with the correct credentials.

' To add resource without drive.
WNet.AddConnection("user", "password", "\\\shared", Nothing)

' To close that connection

Open in new window

knk53Author Commented:
I sent
this responds with error 1326.
 I can go to the command line and type
NET USE \\mycomputer\share /user:myusername <enter>  then type
NET USE  <enter>   and see
STATUS                                  LOCAL                     REMOTE
  OK                                                                              \\mycomputer\share
I know the credentials are working, but why does wnetaddconnection2 return an error???
You might have to specify a password if you didnt add the everyone group or anonymous logon group permissions to the share. How is your share setup with groups/permissions?
Everyone group does not include anonymous security identifier. 
knk53Author Commented:
I tried your calling method and it did work with the word NOTHING.  Then I replaced the word Nothing with the "" and it still passed.   I think the NOTHING is the correct answer.   It is possible that, once you have logged onto a share using the API the next time you logon it may accept the "".
That appears to be the case because you are already connected so it might not even verify the password in that case. If you cancel the connection then it wouldn't already exists and would most likely fail using "" when working with the API you need make sure you pass NULL string which can be accomplished using Nothing OR vbNullString.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.