Solved

Attempt to connect to network share with wnetaddconnection2 fails error 1326

Posted on 2010-08-31
9
2,675 Views
Last Modified: 2012-05-10
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
    'DWSCOPE
    Public Const RESOURCE_CONNECTED As Integer = &H1
    Public Const RESOURCE_GLOBALNET As Integer = &H2
    Public Const RESOURCE_REMEMBERED As Integer = &H3
    'DWTYPE
    Public Const RESOURCETYPE_ANY As Integer = &H0
    Public Const RESOURCETYPE_DISK As Integer = &H1
    Public Const RESOURCETYPE_PRINT As Integer = &H2
    'DWDISPLAYTYPE
    Public Const RESOURCEDISPLAYTYPE_GENERIC As Integer = &H0
    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
      netrs.dDispType = Win32API.RESOURCEDISPLAYTYPE_SHARE
        netrs.dUsage = Win32API.RESOURCEUSAGE_CONNECTABLE

         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
      Else
         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???????????

 

0
Comment
Question by:knk53
  • 6
  • 3
9 Comments
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33567538
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
        Try
            WNet.AddConnection("user", "password", "\\192.168.1.101\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
        RESOURCETYPE_ANY
        RESOURCETYPE_DISK
        RESOURCETYPE_PRINT
        RESOURCETYPE_RESERVED
    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
        Get
            Return _pLocal
        End Get
    End Property

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

End Class

Open in new window

0
 
LVL 29

Expert Comment

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

Open in new window

0
 
LVL 2

Author Comment

by:knk53
ID: 33568371
eql1044,
   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.    
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33568623
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", "\\192.168.1.104\shared", Nothing)

' To close that connection
WNet.CancelConnection(WNet.RemoteName)

Open in new window

0
 
LVL 2

Author Comment

by:knk53
ID: 33568747
I sent
   WNET.AddConnection("myusername","","\\mycomputer\share","")
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???
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33568937
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.
http://support.microsoft.com/kb/278259 
0
 
LVL 29

Accepted Solution

by:
nffvrxqgrcfqvvc earned 500 total points
ID: 33569052
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, "\\192.168.1.104\shared", Nothing)

Open in new window

0
 
LVL 2

Author Comment

by:knk53
ID: 33569380
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 "".
0
 
LVL 29

Expert Comment

by:nffvrxqgrcfqvvc
ID: 33569481
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.
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
If you're writing a .NET application to connect to an Access .mdb database and use pre-existing queries that require parameters, you've come to the right place! Let's say the pre-existing query(qryCust) in Access takes a Date as a parameter and l…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question