使用sftp将文件上载到服务器主机

时间:2016-06-13 13:31:02

标签: c# file sockets sftp

我目前收到此错误:

  

未处理的异常:System.Net.SocketsExceptions:没有这样的主机   已知...

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

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

1 个答案:

答案 0 :(得分:0)

当我在主机名中加入“ftp://”和“sftp://”时,我遇到了类似的问题。在我的搜索中谷歌让我来到这里。这是因为我从FtpWebRequest切换到 SSH.Net ,其中我的主机值以前是网址。

我将以下代码作为工作主机名值的示例。其他人也可以使用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();
}