2017-08-29 41 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