c# - 使用sftp将文件上传到服务器主机

标签 c# file sockets sftp

我目前遇到这个错误:

Unhandled Exception: System.Net.SocketsExceptions: No such host is known...

不太清楚那是什么意思,但这就是我所做的。

public FileUploader(/*string host, string port, string username, string password,*/ string fileLocation)
    {
      string temp;
      Console.Write("Server URL:");
      this.host = Console.ReadLine();
      Console.Write("Server Port:");
      temp = Console.ReadLine();
      this.port = int.Parse(temp);
      Console.Write("Username:");
      this.username = Console.ReadLine();
      Console.Write("Password:");
      this.password = ReadPassword();
      Console.Write("Folder Location:");
      this.fileLocation = Console.ReadLine();
    }

    public void UploadFile(string pathToFile)
    {
      var client = new SftpClient(host, port, username, password);
      client.Connect();
      var fileStream = new FileStream(pathToFile, FileMode.Open);
      client.BufferSize = 4 * 1024;
      client.UploadFile(fileStream,fileLocation, null);
      client.Disconnect();
      client.Dispose();
    }

最佳答案

当我在主机名 中包含“ftp://”和“sftp://”时,我遇到了类似的问题。在我的搜索中,谷歌将我带到了这里。这是因为我从 FtpWebRequest 切换到 SSH.Net,我的主机值以前是一个 url。

我将以下代码作为工作主机名值的示例。其他人也可以改用 IP 地址。

const string sFtpHost = "someprefix.somedomain.com";
const int sFtpPort = 22;
const string userName = "SomeUser";
const string password = "SomePassword";

// ...

string localFileName = SomeFileName;
string remoteFileName = @"/SomeSubFolder/" + System.IO.Path.GetFileName(localFileName);

using (var sftp = new SftpClient(sFtpHost, sFtpPort, userName, password))
{
    sftp.Connect();

    using (var file = File.OpenRead(localFileName))
    {
        sftp.UploadFile(input: file, path: remoteFileName, canOverride: true);
    }

    sftp.Disconnect();
}

关于c# - 使用sftp将文件上传到服务器主机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791123/

相关文章:

c++ - 使用 boost::asio 编写简单的文件传输程序。有主要的发送\接收不同步

C#跨线程通信

c# - 如何在 [InitializeOnLoad] 脚本类型中更改游戏对象在层次结构中的位置?

file - 在 R 中的 csv 文件的不同列中写入多个值

java - 在java中将文件重命名为另一个文件

c - Linux 中 TCP 连接异常缓慢

c# - 过多调试输出 "Event X was called with Y arguments, but it is defined with Z parameter(s)"的解决方法

c# - 如果在 C# 中收到新的 Outlook 邮件,则启动方法

file - 如何在 Common Lisp 中进行批量文件编辑?

使用 stoppbit 的 Python 套接字