2011-05-09 122 views
2

我正在使用System.IO.File.Copy将文件复制到远程服务器上的c $。我需要指定连接的用户名/密码。有没有简单的方法来做到这一点?我曾希望System.IO.File.Copy将接受凭据作为参数,但它不。我怎样才能做到这一点?VB.NET System.IO.File.Copy问题

回答

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 
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 

Credits去Ganeshyb

+0

谢谢。和WOW。对于那些显然应该是Copy方法的内建函数的东西,这是难以置信的复杂。这是唯一的方法吗?我只是相信MS会想到这个,并且包含一个更简单的方法。 – 2011-05-09 13:04:03

+0

此外,请检查此:http://msdn.microsoft.com/en-us/library/6485ct6t(vs.71).aspx(对于更复杂的东西):) – Stefan 2011-05-09 13:16:23

+0

而这里有另一种解决方案:http://social。 msdn.microsoft.com/Forums/en-US/vbgeneral/thread/b732f49a-5aa8-4a9d-8f88-35d7f235a082/ – Stefan 2011-05-09 13:19:29