SFTP/FTPS file transfers in Microsoft Azure Function

To use WinSCP .NET assembly to implement an SFTP/FTP functionality in Microsoft Azure Function, just add WinSCP NuGet package to your Azure Functions project in Visual Studio and then use any standard WinSCP code.

The only problem you will face is, that for some reason, when publishing the project to an Azure storage, winscp.exe dependency is stored to the root folder of the function, instead of the bin subfolder along with other binaries (particularly the WinSCPnet.dll).

To overcome that, you need to use Session.ExecutablePath to point to the actual location of winscp.exe. You can use ExecutionContext.FunctionAppDirectory to refer to the root folder of the function. To get an instance of the ExecutionContext, add new parameter to the signature of your entry method (usually Run).

The following example is for version 2.x of Azure Functions:

[FunctionName("Function1")]
public static void Run(
    [TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log, ExecutionContext context)
{
    try
    {
        log.LogInformation("Starting");
 
        SessionOptions sessionOptions = new SessionOptions();
        // setup sessionOptions 
 
        using (Session session = new Session())
        {
            // Look for winscp.exe in the root folder of the function
            session.ExecutablePath = Path.Combine(context.FunctionAppDirectory, "winscp.exe");
 
            log.LogInformation("Connecting");
            session.Open(sessionOptions);
 
            // ...
        }
        log.LogInformation("Done");
    }
    catch (Exception e)
    {
        log.LogError(e, "Error");
    }
}

For version 1.x of Azure functions, the code is basically the same. Just for logging, you need to use TraceWriter instead of ILogger. Read about Migrating from version 1.x.

Last modified: by martin