Use SFTP instead of FTP in older version of C# (2010 Express)

一曲冷凌霜 提交于 2020-01-14 06:13:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/58524441/use-sftp-instead-of-ftp-in-older-version-of-c-sharp-2010-express

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!