【问题标题】:Use SFTP instead of FTP in older version of C# (2010 Express)在旧版本的 C# (2010 Express) 中使用 SFTP 而不是 FTP
【发布时间】:2019-10-23 13:51:33
【问题描述】:

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

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

任何建议/帮助将不胜感激。

【问题讨论】:

    标签: c# .net ftp sftp


    【解决方案1】:

    要使用 SSH.NET 将文件上传到 SFTP 服务器,请使用 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 完全不同。你基本上必须从头开始。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-15
      • 2018-03-29
      • 2011-05-13
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多