Reputation: 847
I have to change an older C# script (created back in 2010 in C# Express) to use SFTP instead of FTP. It took some doing to get this script out of an old repository - and to download a version of C# 2010 Express to get the script open! But I finally managed it. I have never coded in C# so please be kind. We have several off-site PCs that need to transfer files to and from the server on their network. This script is a .dll which is referenced in several other programs on these systems, so I'll need to change the calls to this .dll in those scripts as well. I have researched using SFTP in C# and from what I've seen thought it was best to install Renci.SshNet, so that has been installed as a reference in the project. What I'm looking to do is change the function below to use SFTP instead of FTP, but I'm not really sure how to even begin -
public TimeSpan FTPTo(string strFTPServer, string strLocalFileandPath, string strFTPFileandPath, string strFTPUser, string strFTPPassword)
{
try
{
DateTime dtStart = DateTime.Now;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(strFTPServer + "/" + strFTPFileandPath);
ftp.Proxy = null;
ftp.Credentials = new NetworkCredential(strFTPUser, strFTPPassword);
//userid and password for the ftp server to given
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
FileStream fs = File.OpenRead(strLocalFileandPath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = ftp.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
return DateTime.Now - dtStart;
}
catch (Exception ex1)
{
throw ex1;
}
}
Any suggestions/help would be greatly appreciated.
Upvotes: 0
Views: 609
Reputation: 202494
To upload a file to an SFTP server using SSH.NET, use SftpClient.UploadFile
.
A trivial example is like:
var client = new SftpClient("example.com", "username", "password");
client.Connect();
using (var sourceStream = File.Open(@"C:\local\path\file.ext"))
{
client.UploadFile(sourceStream, "/remote/path/file.ext");
}
There's no relation to your original code. The API is completely different. You basically have to start from the scratch.
Upvotes: 2