我正在使用System.IO.File.Copy将文件复制到远程服务器上的c $。我需要为连接指定用户名/密码。有一个简单的方法吗?我曾希望System.IO.File.Copy接受凭证作为参数,但事实并非如此。我怎么能这样做?
答案 0 :(得分:1)
您无法将凭据添加到system.io.file,但似乎有一种解决方法: http://forums.asp.net/t/1283577.aspx/1
以上链接的片段:
using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr))
{
//do your IO operations
ctx.Undo();
}
转换为vb.net:
Using ctx As System.Security.Principal.WindowsImpersonationContext = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr)
'do your IO operations
ctx.Undo()
End Using
积分转到Ganeshyb
答案 1 :(得分:1)
绝对最简单的做法是将此例程添加到您的代码中,然后在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