I have a program which needs to put data on a network share. In some cases, the user has no access through his account, and would need to provide credentials to login.
My idea was to have the program popup the windows credential screen so the user can login (like when the user would open the share through windows explorer).
I found the WNetUseConnection
API which would allow to login to the share without mapping it, and it has options to give a prompt.
This is the code I'm using:
Public Class frmMain
Private Const CONNECT_INTRERACTIVE = &H8
Private Const CONNECT_PROMPT = &H10
Private Const RESOURCETYPE_DISK = &H1
Private Structure NETRESOURCE
Public dwScope As Long
Public dwType As Long
Public dwDisplayType As Long
Public dwUsage As Long
Public lpLocalName As String
Public lpRemoteName As String
Public lpComment As String
Public lpProvider As String
End Structure
Private Declare Function WNetUseConnection Lib "mpr.dll" _
Alias "WNetUseConnectionA" ( _
ByVal hwndOwner As Long, _
ByRef lpNetResource As NETRESOURCE, _
ByVal lpUsername As String, _
ByVal lpPassword As String, _
ByVal dwFlags As Long, _
ByVal lpAccessName As String, _
ByRef lpBufferSize As Long, _
ByRef lpResult As Long) _
As Long
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim resource As New NETRESOURCE
Dim success As Long
Dim ErrInfo As Long
With resource
.dwType = RESOURCETYPE_DISK
.lpLocalName = vbNullString
.lpRemoteName = "\\server\folder\"
.lpProvider = vbNullString
End With
ErrInfo = WNetUseConnection(Me.Handle, resource, "", "", CONNECT_INTRERACTIVE Or CONNECT_PROMPT, vbNull, vbNull, success)
Console.WriteLine(ErrInfo)
Dim errorMessage As String
errorMessage = New Win32Exception().Message
Console.WriteLine(errorMessage)
End Sub
The error I'm getting back is:
The handle is invalid (code 2091649073639).
Is there a way to get this working?