private void CopyFilesToSharedLocation1()
{
IntPtr admin_token = default(IntPtr);
WindowsIdentity wid_admin = null;
WindowsImpersonationContext wic = null;
try
{
MessageBox.Show("Copying file...");
// username,fully qualified computer name,pwd,9,0,admin_token
if (LogonUser("testjay", "abc.xyz.com", "test1234", 9, 0, ref admin_token) != 0)
{
wid_admin = new WindowsIdentity(admin_token);
wic = wid_admin.Impersonate();
System.IO.File.Copy("C:\\DATAFolder\\images\\EECT2H.jpg", "\\\\123.22.134.20\\TestJayFolder\\EECT2H.jpg", true);
MessageBox.Show("Copy succeeded");
}
else
{
MessageBox.Show("Copy Failed");
}
}
catch (System.Exception se)
{
int ret = Marshal.GetLastWin32Error();
MessageBox.Show(ret.ToString(), "Error code: " + ret.ToString());
MessageBox.Show(se.Message);
}
finally
{
if (wic != null)
{
wic.Undo();
}
}
}
// obtains user token
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(string pszUsername, string pszDomain, string pszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
VB.Net---------------------
Imports System
Imports System.Runtime.InteropServices
Imports System.Security.Principal
Imports System.Security.Permissions
Public Class Form1
<DllImport("advapi32.DLL", SetLastError:=True)> _
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
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim admin_token As IntPtr
Dim wid_current As WindowsIdentity = WindowsIdentity.GetCurrent()
Dim wid_admin As WindowsIdentity = Nothing
Dim wic As WindowsImpersonationContext = Nothing
Try
MessageBox.Show("Copying file...")
If LogonUser("Local Admin name", "Local computer name", "pwd", 9, 0, admin_token) <> 0 Then
wid_admin = New WindowsIdentity(admin_token)
wic = wid_admin.Impersonate()
System.IO.File.Copy("C:\right.bmp", "\\157.60.113.28\testnew\right.bmp", True)
MessageBox.Show("Copy succeeded")
Else
MessageBox.Show("Copy Failed")
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)
Finally
If wic IsNot Nothing Then
wic.Undo()
End If
End Try
End Sub
End Class