I have a windows form that connects to a Database to retrieve variables. The connection is fine and I set the variables in the datagridview. Important variables are fromDirectory, fromDirectoryInfo, toDirectory and toDirectoryInfo.

The fromDirectory is a network folder that needs to be authenticated before accessing it, same with the toDirectory. The ~~Info data is the username and passwords for the network directory. Everything up to this point works fine. The problem is with the Network Credentials not working, no matter what I try or what I find as resources online. I get the continued error of the user name or password is incorrect even when I statically type them directly in the code. The user name and password are correct because if I go to the folder directly and enter the same, I can access the folder.

Here is the code with the issue:


'Example of variables for reference. These variables are set from the data in the database as strings.

fromDir = "\\10.10.10.4\d$\Test\FromDirectory"
toDir = "\\100.11.5.37\d$\Test\ToDirectory"

'The username and password is the same - for example: 

fromDirUser = "admin"
fromDirPwd = "Test1234"

toDirUser = "admin"
toDirPwd = "Test1234"

**Dim fromDirCred As New NetworkCredential(fromDirUser, fromDirPwd, fromDir)
Dim fromDirCache As New CredentialCache()
Dim toDirCred As New NetworkCredential(toDirUser, toDirPwd, toDir)
Dim toDirCache As New CredentialCache()
fromDirCache.Add(New Uri(fromDir), "Basic", fromDirCred)
toDirCache.Add(New Uri(toDir), "Basic", toDirCred)**


'This TRY/CATCH is just for testing. In reality, after authenticated it will need to copy all files from the fromDir to the authenticated toDir.

Try

    Dim dir As New DirectoryInfo(fromDir)
    For Each fi As FileInfo In dir.GetFiles("*.*")
        MessageBox.Show(fi.ToString())
    Next
Catch ex As IOException
    MsgBox(ex.Message)
End Try

If anyone can help with this, that would be greatly appreciated. I have read the MS Docs and set up the authentication as exampled but still not working.

I have tried every possible resource I found without a complete solution. I am fairly good with VB.NET but not very good with security access. The expectation is that the folders will be accessed using the NetwordCredentials and after being able to access them, I will be able to copy files across the folders.

1

There are 1 answers

0
John On BEST ANSWER

This ended up being the solution that worked for me. Using Impersonation with the script in the link below allowed me to access the network folders by passing the username and password.

Impersonate a Windows or Active Directory user from a different, untrusted domain