Hi,
Another way to do that: try connecting to the share by using WNet functions, the WNetAddConnection3 function will popup a standard system dialog asking for credential to logon the target machine. Once connected, you can copy your files. And then you can cancel the connection when copy is done. The benefit of this approach is, you don't need to worry about securing the password. The system takes care of it.
I wrote some VB.NET sample code for you:
<StructLayout(LayoutKind.Sequential)> _
Private Structure NETRESOURCE
Public dwScope As Integer
Public dwType As Integer
Public dwDisplayType As Integer
Public dwUsage As Integer
<MarshalAs(UnmanagedType.LPTStr)> _
Public lpLocalName As String
<MarshalAs(UnmanagedType.LPTStr)> _
Public lpRemoteName As String
<MarshalAs(UnmanagedType.LPTStr)> _
Public lpComment As String
<MarshalAs(UnmanagedType.LPTStr)> _
Public lpProvider As String
End Structure
Private Const RESOURCETYPE_DISK As Integer = &H1
Private Const CONNECT_INTERACTIVE As Integer = &H8
Private Const CONNECT_PROMPT As Integer = &H10
Private Const NO_ERROR As Integer = &H0
Private Declare Auto Function WNetAddConnection3 Lib "mpr.dll" ( _
ByVal hwndOwner As IntPtr, _
<MarshalAs(UnmanagedType.Struct)> ByRef lpNetResource As NETRESOURCE, _
ByVal lpPassword As String, _
ByVal lpUserName As String, _
ByVal dwFlags As Integer) As Integer
Private Declare Auto Function WNetCancelConnection2 Lib "mpr.dll" ( _
ByVal lpName As String, _
ByVal dwFlags As Integer, _
ByVal fForce As Boolean) As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim result As Integer
Dim res As New NETRESOURCE
' txtSharePath contains the target path like \\myserver\share
Dim remoteName As String = txtSharePath.Text.Trim()
Try
' Connect to the remote resouce...
res.dwType = RESOURCETYPE_DISK
res.lpRemoteName = remoteName
' Connect to the remote machine.
' Users will be asked for credentials if necessary.
result = WNetAddConnection3(Me.Handle, res, Nothing, Nothing, CONNECT_INTERACTIVE Or CONNECT_PROMPT)
CheckResult(result)
' do your copy here...
' File.Copy(...)
' Cancel the connection
result = WNetCancelConnection2(txtSharePath.Text, 0, True)
CheckResult(result)
Catch ex As Win32Exception
MsgBox(ex.Message, MsgBoxStyle.Critical Or MsgBoxStyle.OkOnly)
End Try
End Sub
Private Sub CheckResult(ByVal result As Integer)
If result <> NO_ERROR Then
Throw New Win32Exception(result)
End If
End Sub
Hope this helps.
Regards,
Jie
MSDN Subscriber Support in Forum
If you have any feedback on our support, please contact msdnmg[at]microsoft.com
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
If you have any feedback, please tell us.
The CodeFx ProjectMy Blog (in Simplified Chinese)