Mapear Rede Drive Programaticamente

eu tenho VB.NET código para mapear uma unidade para um caminho de rede.

strPath = "\\11.22.33.11\Hostsw\Host\SW\"  

quando ligo para MapDrive("T", strpath, "pcs", "$pcspcs$") usando a função abaixo, erra com a mensagem "Bad path could not connect to Star Directory".

Public Declare Function WNetAddConnection2 Lib "mpr.dll" Alias "WNetAddConnection2A" (ByRef lpNetResource As NETRESOURCE, ByVal lpPassword As String, ByVal lpUserName As String, ByVal dwFlags As Integer) As Integer
        Public Declare Function WNetCancelConnection2 Lib "mpr" Alias "WNetCancelConnection2A" (ByVal lpName As String, ByVal dwFlags As Integer, ByVal fForce As Integer) As Integer
        Public Const ForceDisconnect As Integer = 1
        Public Const RESOURCETYPE_DISK As Long = &H1
        Private Const ERROR_BAD_NETPATH = 53&
        Private Const ERROR_NETWORK_ACCESS_DENIED = 65&
        Private Const ERROR_INVALID_PASSWORD = 86&
        Private Const ERROR_NETWORK_BUSY = 54&

        Public Structure NETRESOURCE
            Public dwScope As Integer
            Public dwType As Integer
            Public dwDisplayType As Integer
            Public dwUsage As Integer
            Public lpLocalName As String
            Public lpRemoteName As String
            Public lpComment As String
            Public lpProvider As String
        End Structure
        Public Function MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String, ByVal strUsername As String, ByVal strPassword As String) As Boolean


            Dim nr As NETRESOURCE

            nr = New NETRESOURCE
            nr.lpRemoteName = UNCPath
            nr.lpLocalName = DriveLetter & ":"
            nr.lpProvider = Nothing
            nr.dwType = RESOURCETYPE_DISK

            Dim result As Integer
            result = WNetAddConnection2(nr, strPassword, strUsername, 0)

            If result = 0 Then
                Return True
            Else
                Select Case result
                    Case ERROR_BAD_NETPATH
                        PostBackMessageHiddenField.Value = "QA4001I Bad path could not connect to Star Directory"
                    Case ERROR_INVALID_PASSWORD
                        PostBackMessageHiddenField.Value = "QA4002I Invalid password could not connect to Star Directory"
                    Case ERROR_NETWORK_ACCESS_DENIED
                        PostBackMessageHiddenField.Value = "QA4003I Network access denied could not connect to Star Directory"
                    Case ERROR_NETWORK_BUSY
                        PostBackMessageHiddenField.Value = "QA4004I Network busy could not connect to Star Directory"
                End Select
                Return False
            End If

        End Function

        Public Function UnMapDrive(ByVal DriveLetter As String) As Boolean
            Dim rc As Integer
            rc = WNetCancelConnection2(DriveLetter & ":", 0, ForceDisconnect)

            If rc = 0 Then
                Return True
            Else
                Return False
            End If 
        End Function
Author: Cœur, 2014-07-17

1 answers

A solução da investigação seria olhar primeiro para as definições P / invocam para os seus métodos

Http://www.pinvoke.net/default.aspx/mpr.wnetaddconnection2
http://pinvoke.net/default.aspx/Structures/NETRESOURCE.html

E certifique-se que as definições dos seus métodos estão correctas. Você, por exemplo, usa Integer em vez de UInt32 e assim por diante.

Uma solução rápida e suja mas eficaz é não reinventar a roda e, em vez disso, usar a ferramenta net incluída em cada instalação do Windows:

Module Module1
Public Sub MapDrive(ByVal DriveLetter As String, ByVal UNCPath As String, ByVal strUsername As String, ByVal strPassword As String)
    Dim p As New Process()
    p.StartInfo.FileName = "net.exe"
    p.StartInfo.Arguments = " use " & DriveLetter & ": " & UNCPath & " " & strPassword & " /USER:" & strUsername
    p.StartInfo.CreateNoWindow = True
    p.Start()
    p.WaitForExit()
End Sub

Sub Main()
    MapDrive("x", "\\FoosServer\FoosShare", "FoosServer\Bob", "correcthorsebatterystaple")
End Sub

End Module

O que o código faz, é que ele executa net.exe (o caminho está incluído na variável de ambiente PATH, por isso não é necessário incluí-lo) com os argumentos adequados (por exemplo net use x: \\Server\share password /USER:domain\Username), e isto então mapeia o seu disco de rede.

 5
Author: Jens, 2014-09-20 20:23:20