theo theo -3 years ago 234
C# Question

Code to download file from FTP with WinSCP .NET assembly does not connect, but I can connect in WinSCP GUI

I need to download a file from FTP thru WinSCP .NET assembly. I have this code currently but the error says Authentication failed.

SessionOptions sessionOptions = new SessionOptions
Protocol = Protocol.Ftp,
HostName = "",
UserName = "usersample",
Password = "P@ssw0rd",
PortNumber = 21

using (Session session = new Session())
// Connect

// Download files
TransferOptions transferOptions = new TransferOptions();
transferOptions.TransferMode = TransferMode.Binary;

TransferOperationResult transferResult;
transferResult =
"/HST/sample.txt", "C:\\Users\\john\\Documents\\SampleFolder\\",
false, transferOptions);

// Throw on any error

// Print results
foreach (TransferEventArgs transfer in transferResult.Transfers)
Console.WriteLine("Download of {0} succeeded", transfer.FileName);


catch (Exception e)
Console.WriteLine("Error: {0}", e);

I got the code from this reference:

Originally, it has the following:

SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

But I removed it since I don't have it and I think it's for SFTP (not sure)
I've tried the credentials manually and they work. I am able to login.
Please help. Thank you.

Answer Source

There's WinSCP FAQ for your kind of situation:
Why I cannot connect/transfer using script, when I can using GUI (or vice versa)?

The easiest solution, to start with, is to use Generate transfer code function from your GUI session, to get a working code template.

  • Login in GUI;
  • Select the file to download in remote panel and the target local directory in local panel;
  • Use Download command;
  • On the Download transfer options dialog, use Transfer settings > Generate Code;
  • Generate transfer code dialog opens. Select the .NET assembly tab and make sure C# language is selected.

    enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download