As a developer, you will have the opportunity to transfer files, such as Excel, CVS, Images, and flat files, to third-party or upstream/downstream systems.

There are different ways to transfer.

Different ways to transfer

  1. Transfer through the SFTP client through an open-source package
  2. File copy method using service account

What are the methods in the open-source package?

  1. Secure File Transfer Protocols
  2. Cloud-Based File Sharing
  3. API’s and Webhooks
  4. Managed File Transfer (MFT)
  5. Email with Encryption
  6. VPN + Network shares
  7. Message Queues or Middleware

In this blog, I will explain the use case and practical implementation of a widely used open-source API for automated, secure file transfers.

Transfer through the SFTP client through an open-source package- SSH.NET

We have popular packages such as SSH.NET, WinSCP.NET, SharpSSH & etc.

In my point of view, for open-source and .NET Core compatibility, SSH.NET is the best choice. It’s lightweight, actively used, and works well for most SFTP needs.

Let’s go for practical implementation

Install NuGet Package: Install-Package SSH.NET

Reference: https://www.nuget.org/packages/ssh.net/

Authentication Method Options

Private Key Authentication Method

using Renci.SshNet;
using System.Text;


//Private key
var key = System.IO.File.ReadAllText("privatekey.ppk");
//sftp_host
var sftp_host = "sftp_server";
//sftp_user
var sftp_username = "sftpuser";
//file to transfer
var file = "C:\\Users\\test.txt";
//sftp_folder directory
var sftp_folderpath = "/appl/data/inbound";
var buf = new MemoryStream(Encoding.UTF8.GetBytes(key));
var privateKeyFile = new PrivateKeyFile(buf);
// Attach the private key while making connection
var connectionInfo = new ConnectionInfo(sftp_host, sftp_username,
    new PrivateKeyAuthenticationMethod(sftp_username, privateKeyFile));

//Connect through Port ( Default Port is 22 )
/*
var connectionbyPort = new
ConnectionInfo
(   string host, 
    int port, 
    string username, 
    params AuthenticationMethod[] authenticationMethods
);
*/

//Connect through Proxy  ( HTTP, SOCKS4, SOCKS5 ).
/*
 * proxyType: Enum ProxyTypes.
   proxyHost, proxyPort, proxyUsername, proxyPassword: Proxy details.
var connectionbyPort = new ConnectionInfo(
    string host,
    int port,
    string username,
    ProxyTypes proxyType,
    string proxyHost,
    int proxyPort,
    string proxyUsername,
    string proxyPassword,
    params AuthenticationMethod[] authenticationMethods);
*/

using (var client = new SftpClient(connectionInfo))
{
    try
    {
        using (FileStream fs = System.IO.File.Open(file, FileMode.Open))
        {
            client.Connect();
            client.UploadFile(fs, sftp_folderpath+ Path.GetFileName(file), null);
            client.Disconnect();
        }
    }
    catch (Exception ex)
    {
        if (client.IsConnected)
            client.Disconnect();
    }
}

Password Authentication Method


string username = "your-username";
string password = "your-password";

//sftp_host
var host = "sftp_server";
int port = 22;

//file to transfer
var file = "C:\\Users\\test.txt";

//sftp_folder directory
var sftp_folderpath = "/appl/data/inbound";



using (var client = new SshClient(host,port,username,password))
{
     
    try
    {
        if(sftp.IsConnected)
          {
            client.Connect();
            Console.WriteLine("Connected successfully!");
                using (FileStream fs = System.IO.File.Open(file, FileMode.Open))
                {
                    client.Connect();
                    client.UploadFile(fs, sftp_folderpath + Path.GetFileName(file), null);
                    client.Disconnect();
              }
        }
    }
    catch (Exception ex)
    {
        if (client.IsConnected)
            client.Disconnect();
    }
 
}

Keyboard Interactive Authentication Method

string username = "your-username";
string password = "your-password";

//sftp_host
var host = "sftp_server";
int port = 22;

//file to transfer
var file = "C:\\Users\\test.txt";

//sftp_folder directory
var sftp_folderpath = "/appl/data/inbound";

// Define the keyboard-interactive authentication method
var keyboardAuth = new KeyboardInteractiveAuthenticationMethod(username);

// Handle the interactive prompts
 keyboardAuth.AuthenticationPrompt += (sender, e) =>
        {
            foreach (var prompt in e .Prompts)
            {
                Console.WriteLine($"Prompt: {prompt.Request}");

                // Automatically respond if the prompt contains 'Password'
                if (prompt.Request.ToLower().Contains("password"))
                {
                    prompt.Response = password;
                }
                // You could add logic here to handle OTP or verification codes
                // else if (prompt.Request.ToLower().Contains("verification code"))
                // {
                //     prompt.Response = "123456"; // Example for OTP
                // }
            }
      };

 // Optionally add password-based auth fallback
 var passwordAuth = new PasswordAuthenticationMethod(username, password);

  // Combine both authentication methods
  var connectionInfo = new ConnectionInfo(
            host,
            port,
            username,
            passwordAuth,
            keyboardAuth
        );

//Transfer file using connection
using (var client = new SftpClient(connectionInfo))
{
    try
    {
        using (FileStream fs = System.IO.File.Open(file, FileMode.Open))
        {
            client.Connect();
            client.UploadFile(fs, sftp_folderpath+ Path.GetFileName(file), null);
            client.Disconnect();
        }
    }
    catch (Exception ex)
    {
        if (client.IsConnected)
            client.Disconnect();
    }
}

File copy method using service account

This approach provides a simple way to transfer files, provided the target system permits creating a service account.
To implement it, create a service account user (similar to a regular user account) and grant it read/write access to the target directory.

//file to transfer
var source = "C:\\Users\\test.txt";

//sftp_folder directory
var target = "/appl/data/inbound";

File.Copy(source, target);

While deploying the solution into the server, you need to log on with this service account user

Windows service logon through a service account user

For Example, in Windows Server - Services ( “services.msc”), we need to log on to that service by using username & password.

In IIS

In Project – Advanced settings – Physical path credentials – Log on with user name & password.

as it is less code-intensive and relies solely on.

Summary

Based on my professional experience, I would say the file copy method is the best way to transfer, which is a less code-intensive implementation, and relies only on the network transfer.

Hope you enjoyed the article!!!