2011-05-09 3 views
2

J'utilise System.IO.File.Copy pour copier un fichier vers c $ sur un serveur distant. J'ai besoin de spécifier le nom d'utilisateur/mot de passe pour la connexion. Y a-t-il un moyen simple de le faire? J'avais espéré que System.IO.File.Copy accepterait les informations d'identification en tant qu'argument mais ce n'est pas le cas. Comment puis-je faire ceci?VB.NET System.IO.File.Copy question

Répondre

1

absolue chose la plus simple à faire est d'ajouter cette routine à votre code puis appelez juste avant votre 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

Vous ne pouvez pas ajouter des informations d'identification à l'system.io.file, mais il semble y avoir une solution de contournement ici: http://forums.asp.net/t/1283577.aspx/1

Snippet de lien ci-dessus:

using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr)) 

{ 
//do your IO operations 
ctx.Undo();  
} 

Converti en vb.net:

Using ctx As System.Security.Principal.WindowsImpersonationContext = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr) 
    'do your IO operations  
    ctx.Undo() 
End Using 

Crédits va à Ganeshyb

+0

Merci. Et WOW. C'est incroyablement complexe pour quelque chose qui devrait évidemment être une fonction intégrée de la méthode Copy. Est-ce le seul moyen? Je dois juste croire que MS aurait pensé à cela et aurait inclus un moyen beaucoup plus simple. –

+0

Vérifiez également ceci: http://msdn.microsoft.com/en-us/library/6485ct6t(vs.71).aspx (pour les choses plus complexes) :) – Stefan

+0

Et voici une autre solution: http: // social. msdn.microsoft.com/Forums/fr-FR/vbgeneral/thread/b732f49a-5aa8-4a9d-8f88-35d7f235a082/ – Stefan