Monday, June 29, 2009

Copy files from remote machine

To copy files from local machine we can simply do


as we are already logged in to the machine.

How to copy the files from a remote machine where we have not logged in?

Here is the solution.

We need to provide domainname, user name and password of the remote machine.


Imports System.Security.Principal
Imports System.Runtime.InteropServices

Public Class Form1
Inherits System.Windows.Forms.Form

'Functions needed to copy files from remote machine

Public Shared Function LogonUser(ByVal lpszUserName As String, ByVal lpszDomain As String, _
ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, _
ByRef phToken As IntPtr) As Integer
End Function

Public Sub copyRemoteFiles(ByVal sourceFile As String, ByVal destFile As String)
Dim admin_token As IntPtr
Dim wid_current As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim wid_admin As WindowsIdentity = Nothing
Dim wic As WindowsImpersonationContext = Nothing

If LogonUser(sUserName, sDomainName, sPassword, 9, 0, admin_token) <> 0 Then
wid_admin = New WindowsIdentity(admin_token)
wic = wid_admin.Impersonate()
If System.IO.File.Exists(sourceFile) Then
System.IO.File.Copy(sourceFile, destFile, True)
Else 'Copy Failed
Exit Sub
End If
Exit Sub
End If
Catch se As System.Exception
Dim ret As Integer = Marshal.GetLastWin32Error()
MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString())
If wic IsNot Nothing Then
End If
Exit Sub
If wic IsNot Nothing Then
End If
End Try

End Sub

'Copy remote file
Private Sub btnCopyFiles_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCopyFiles.Click

Dim sourceFile As String
Dim destFile as String

sourceFile = txtSourceFile.Text.Trim 'Remote File Path
destFile = txtDestFile.Text.Trim 'Local File Path

'Copy remote file to local file
copyRemoteFiles(sourceFile, destFile)

End Sub

End Class


No comments:

Post a Comment