在旧版本的C#(2010 Express)中使用SFTP代替FTP [英] Use SFTP instead of FTP in older version of C# (2010 Express)

查看:103
本文介绍了在旧版本的C#(2010 Express)中使用SFTP代替FTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须更改一个较旧的C#脚本(早在2010年在C#Express中创建),以使用SFTP而不是FTP.花了一些功夫才能从旧存储库中删除此脚本-并下载了C#2010 Express版本以将脚本打开!但是我终于做到了.我从未用C#编写过代码,因此请保持友好.我们有几台异地PC,它们需要在其网络上的服务器之间来回传输文件.该脚本是一个.dll,在这些系统上的其他几个程序中也引用了该脚本,因此,我也需要在这些脚本中更改对该.dll的调用.我已经研究过在C#中使用SFTP,并且据我所知,最好安装Renci.SshNet,因此已将其安装为项目中的参考.我想做的是将下面的功能更改为使用SFTP而不是FTP,但是我不确定如何开始-

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.

推荐答案

要使用SSH.NET将文件上传到SFTP服务器,请使用SftpClient.UploadFile.

To upload a file to an SFTP server using SSH.NET, use SftpClient.UploadFile.

一个简单的例子是:

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");
}


与您的原始代码无关. API完全不同.您基本上必须从头开始.

这篇关于在旧版本的C#(2010 Express)中使用SFTP代替FTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆