2012-07-13 33 views
0

任何人都可以幫助我使用C#中的代碼段將本地計算機上的文件傳輸到使用PSCP(PuTTY)傳輸方法的遠程服務器上嗎?我真的很感謝幫助。 謝謝C#中用於文件傳輸的PuTTY

+1

有很多用於.NET的SFTP客戶端組件,包括免費的和商業的。爲什麼使用膩子? – 2012-07-13 14:36:57

+0

[SCP for C#]的可能重複(http://stackoverflow.com/questions/651399/scp-for-c-sharp) – 2012-07-13 14:46:41

回答

1

您可以使用支持SCP的庫,如SSHNetWinSCP。兩者都提供樣本和測試來證明它們的工作方式。

隨着SSH.Net您可以使用此代碼(從測試文件)上傳文件:

using (var scp = new ScpClient(host, username, password)) 
{ 
    scp.Connect(); 
    scp.Upload(new FileInfo(filename), Path.GetFileName(filename)); 
    scp.Disconnect(); 

}

隨着WinSCP賦予庫中的代碼如下所示(從samples):

SessionOptions sessionOptions = new SessionOptions { 
      Protocol = Protocol.Sftp, 
      HostName = "example.com", 
      UserName = "user", 
      Password = "mypassword", 
      SshHostKey = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" 
}; 

using (Session session = new Session()) 
{ 
    // Connect 
    session.Open(sessionOptions); 

    // Upload files 
    TransferOptions transferOptions = new TransferOptions(); 
    transferOptions.TransferMode = TransferMode.Binary; 

    TransferOperationResult transferResult; 
    transferResult = session.PutFiles(@"d:\toupload\*", "/home/user/", false, transferOptions); 

    // Throw on any error 
    transferResult.Check(); 

} 
+0

感謝您的回覆。我仍然對我的需求感到困惑。客戶要求他們需要使用PuTTY SCP技術傳輸文件。我不知道這與其他SCP技術有什麼不同。您能否或其他人請告訴我或解釋在這種情況下應該怎麼做?我讚賞你的回覆。謝謝。 – Suresh 2012-07-16 14:04:04

0

使用SFTPSCP與.NET庫支持的客戶端可能是最好的選擇。但這裏有一個簡單的使用方法:PSCP

Process cmd = new Process(); 
cmd.StartInfo.FileName = @"C:\PuTTY\pscp.exe"; 
cmd.StartInfo.UseShellExecute = false; 
cmd.StartInfo.RedirectStandardInput = true; 
cmd.StartInfo.RedirectStandardOutput = true; 
string argument = @"-pw pass C:\testfile.txt [email protected]:/home/usr"; 
cmd.StartInfo.Arguments = argument; 

cmd.Start(); 
cmd.StandardInput.WriteLine("exit"); 
string output = cmd.StandardOutput.ReadToEnd();