theo theo - 1 month ago 13
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.

try
{
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "172.xx.xxx.xx",
UserName = "usersample",
Password = "P@ssw0rd",
PortNumber = 21
};

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

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

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

// Throw on any error
transferResult.Check();

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

Console.ReadLine();
}


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

I got the code from this reference: https://winscp.net/eng/docs/library_session_getfiles

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