2017-08-29 39 views
0

我目前正在做一个小的应用程序,它从主源文件夹复制到网络上的计算机上的其他文件夹分配图像,但所有其他电脑文件夹需要登录我目前将它们存储在SQL中的凭据。使用Directory.GetFiles

这里一看就是在我需要的行:

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

正如你可以看到我需要阅读的文件,我访问的每个文件夹中的计数。目前,我无法找到一种方式来使用相同的功能,同时提供存储在SQL中的凭证。

更新#1:我没有提到马平驱动器不能因为域策略的使用。

+0

你是什么意思?代码正常工作。 – Subaz

+1

你看过这些问题吗?他们应该指出你正确的方向:https://stackoverflow.com/questions/295538/how-to-provide-user-name-and-password-when-connecting -to-a-network-share和https://stackoverflow.com/questions/2563724/accessing-password-protected-network-drives-in-windows-in-c – pstrjds

+0

这是另一个可能有帮助的非现场资源。它也在C#中,但应该是相当简单的移植到VB - http://www.mobilemotion.eu/?p=1582 – pstrjds

回答

1

好吧,我发现我的解决方案及其在C#中的移植代码vb.net由@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