2011-05-09 43 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