在需要登录凭据的网络共享文件夹上使用Directory.GetFiles

时间:2017-08-29 06:00:35

标签: vb.net networking

我目前正在尝试创建一个小应用程序,将主源文件夹中的图像分发到网络上的计算机上的其他文件夹,但所有其他计算机文件夹都需要登录凭据,我目前将它们存储在SQL中。

这是查看我需要的行:

fileCount = Directory.GetFiles(My.Settings.path212 + "\", "*.jpg", SearchOption.TopDirectoryOnly).Length()

如您所见,我需要读取我正在访问的每个文件夹中的文件数。目前,在提供存储在SQL中的凭据时,我无法找到使用相同功能的方法。

更新#1:我没有提到由于域策略而无法使用maping驱动器。

1 个答案:

答案 0 :(得分:1)

我已经找到了我的解决方案,它是一个从C#移植到vb.net givin的代码@pstrjds。并且只需要分享它。

在课程中添加以下内容:

<DllImport("advapi32.dll", SetLastError := True)> _
Private Shared Function LogonUser(lpszUsername As String, lpszDomain As     String, lpszPassword As String, dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As IntPtr) As Boolean
End Function

<DllImport("kernel32.dll")> _
Private Shared Function CloseHandle(hObject As IntPtr) As [Boolean]
End Function

以下是用法:

Dim token As IntPtr = IntPtr.Zero
LogonUser("username", "remotemachine-name/ipaddress", "password", 9, 0, token)
Using person As WindowsImpersonationContext = New WindowsIdentity(token).Impersonate()
    Try
        fileCount = Directory.GetFiles(My.Settings.path212 + "\", "*.jpg", SearchOption.TopDirectoryOnly).Length()
    Catch ex As IOException
        MsgBox(ex.Message)
    Finally
        person.Undo()
        CloseHandle(token)
    End Try
End Using
相关问题