System.IO.File.Copy()
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.
[CODE]
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
Try
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
Else
Exit Sub
End If
Catch se As System.Exception
Dim ret As Integer = Marshal.GetLastWin32Error()
MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString())
MessageBox.Show(se.Message)
If wic IsNot Nothing Then
wic.Undo()
End If
Exit Sub
Finally
If wic IsNot Nothing Then
wic.Undo()
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
[/CODE]
No comments:
Post a Comment