Search code examples
c#urlftpwinscpwinscp-net

Use URL instead of hostname with WinSCP .NET assembly


I am using WinSCP to upload a file to an FTP host. But I only had ftp://xxx.xx.xx.xx path, not hostname like ftp.example.com. Can I use ftp://xxx.xx.xx.xx for hostname?

My code is based on

SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Ftp,
    HostName = "example.com",
    UserName = "user",
    Password = "mypassword",
};

// Configure proxy
sessionOptions.AddRawSettings("ProxyMethod", "3");
sessionOptions.AddRawSettings("ProxyHost", "proxy");

using (Session session = new Session())
{
    // Connect
    session.Open(sessionOptions);

    // Upload file
    string localFilePath = @"C:\path\file.txt";
    string pathUpload = "/file.txt";
    session.PutFiles(localFilePath, pathUpload).Check();
}

Solution

  • The ftp://xxx.xx.xx.xx URL specify that you want to connect with FTP protocol to xxx.xx.xx.xx host.

    That's what you do in WinSCP .NET assembly by setting SessionOptions.Protocol and SessionOptions.HostName:

    var sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Ftp,
        HostName = "xxx.xx.xx.xx",
        ...
    };
    

    Or you can use SessionOptions.ParseUrl:

    var sessionOptions = new SessionOptions();
    sessionOptions.ParseUrl("ftp://xxx.xx.xx.xx");
    ...