I'm using System.开发者_运维问答IO.File.Copy to copy a file to c$ on a remote server. I need to specify username/password for the connection. Is there a simple way to do this? I had hoped that System.IO.File.Copy would accept credentials as an argument but it doesn't. How can I do this?
You cant add credentials to the system.io.file but there seems to be a workaround here: http://forums.asp.net/t/1283577.aspx/1
Snippet from above link:
using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr))
{
//do your IO operations
ctx.Undo();
}
Converted to vb.net:
Using ctx As System.Security.Principal.WindowsImpersonationContext = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr)
'do your IO operations
ctx.Undo()
End Using
Credits goes to Ganeshyb
Absolute simplest thing to do is to add this routine to your code then call it right before your File.Copy:
Private Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUsername As String, ByVal strPassword As String)
'//====================================================================================
'//using NET USE to open a connection to the remote computer
'//with the specified credentials. if we dont do this first, File.Copy will fail
'//====================================================================================
Dim ProcessStartInfo As New System.Diagnostics.ProcessStartInfo
ProcessStartInfo.FileName = "net"
ProcessStartInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword
ProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden
System.Diagnostics.Process.Start(ProcessStartInfo)
'//============================================================================
'//wait 2 seconds to let the above command complete or the copy will still fail
'//============================================================================
System.Threading.Thread.Sleep(2000)
End Sub
精彩评论