Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17


Attempt to connect to network share with wnetaddconnection2 fails error 1326

Posted on 2010-08-31
Medium Priority
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
    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???????????


Question by:knk53
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 6
  • 3
LVL 29

Expert Comment

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

LVL 29

Expert Comment

ID: 33567677
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


Author Comment

ID: 33568371
   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.    
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

LVL 29

Expert Comment

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", "\\\shared", Nothing)

' To close that connection

Open in new window


Author Comment

ID: 33568747
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???
LVL 29

Expert Comment

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. 
LVL 29

Accepted Solution

nffvrxqgrcfqvvc earned 2000 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, "\\\shared", Nothing)

Open in new window


Author Comment

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 "".
LVL 29

Expert Comment

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.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

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

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Introduction When many people think of the WebBrowser ( control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

721 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