This topic should help you:
access a directory in a domain by username and password
Instead of using the global impersonation context, we create a local one to access the resource, then destroyed it at the end. Exactly as if the parameters were transmitted directly. We don't really have alternative as there is no way to transmit security information with the directoryinfo instance.
example :
Imports System.IO
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Public Class testDirAccess
'Impersonation functionality
<DllImport("advapi32.dll", SetLastError:=True)>
Private Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
End Function
'Disconnection after file operations
<DllImport("kernel32.dll")>
Private Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean
End Function
Sub test()
Const LOGON_TYPE_NEW_CREDENTIALS As Integer = 9
Const LOGON32_PROVIDER_WINNT50 As Integer = 3
'User token that represents the authorized user account
Dim token As IntPtr = IntPtr.Zero
Dim result As Boolean = LogonUser("username", "domainname", "password", LOGON_TYPE_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, token)
If result = True Then
'Use token to setup a WindowsImpersonationContext
Using ctx As WindowsImpersonationContext = (New WindowsIdentity(token)).Impersonate()
'Your file operations
Dim files() As String = Directory.GetFiles("\\remotemachine\share\folder")
'Release the context, and close user token
ctx.Undo()
CloseHandle(token)
End Using
End If
End Sub
End Class