Simple Application To Transfer File From Localhost To SFTP

Learn simple application to transfer file from localhost to sftp with practical examples, diagrams, and best practices. Covers c#, winforms, visual-studio-2010 development techniques with visual ex...

Simple C# WinForms Application for SFTP File Transfer

Hero image for Simple Application To Transfer File From Localhost To SFTP

Learn how to create a basic C# WinForms application to securely transfer files from your local machine to an SFTP server using the SSH.NET library.

Transferring files securely to a remote server is a common requirement in many applications. SFTP (SSH File Transfer Protocol) provides a robust and encrypted method for this. This article guides you through building a simple C# WinForms application that can connect to an SFTP server, authenticate, and upload a file from your localhost. We'll be using the popular open-source SSH.NET library, which simplifies SFTP operations in .NET applications.

Prerequisites and Setup

Before diving into the code, ensure you have the necessary tools and libraries. This guide assumes you are using Visual Studio 2010 or later, targeting .NET Framework 4.0 or higher. The core component for SFTP connectivity will be the SSH.NET library, which needs to be added to your project.

1. Create a New WinForms Project

Open Visual Studio and create a new 'Windows Forms Application' project. Name it something descriptive, like SFTPFileTransferApp.

2. Install SSH.NET via NuGet

In Visual Studio, go to Tools > NuGet Package Manager > Manage NuGet Packages for Solution.... Search for SSH.NET and install it into your project. This will add the necessary references to your project.

3. Design the User Interface

Open Form1.cs in design view. Add the following controls to your form:

  • TextBox for SFTP Host (txtHost)
  • TextBox for Username (txtUsername)
  • TextBox for Password (txtPassword), set UseSystemPasswordChar to true
  • TextBox for Local File Path (txtLocalFilePath)
  • Button to browse for local file (btnBrowseLocalFile)
  • TextBox for Remote File Path (txtRemoteFilePath)
  • Button to initiate transfer (btnTransfer)
  • Label or TextBox for status messages (lblStatus or txtStatus)
flowchart TD
    A[Start Application] --> B{User Input SFTP Details}
    B --> C[User Selects Local File]
    C --> D[User Specifies Remote Path]
    D --> E[Click 'Transfer' Button]
    E --> F{Establish SFTP Connection}
    F -- On Success --> G[Authenticate User]
    G -- On Success --> H[Upload File]
    H -- On Success --> I[Display Success Message]
    I --> J[End]
    F -- On Failure --> K[Display Error]
    G -- On Failure --> K
    H -- On Failure --> K

SFTP File Transfer Process Flow

Implementing the File Transfer Logic

The core logic involves connecting to the SFTP server, authenticating, and then using the SftpClient object to upload the file. Error handling is crucial for a robust application.

using System;
using System.IO;
using System.Windows.Forms;
using Renci.SshNet;

namespace SFTPFileTransferApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowseLocalFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    txtLocalFilePath.Text = openFileDialog.FileName;
                }
            }
        }

        private async void btnTransfer_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "Transferring...";
            lblStatus.ForeColor = System.Drawing.Color.Blue;

            string host = txtHost.Text;
            string username = txtUsername.Text;
            string password = txtPassword.Text;
            string localFilePath = txtLocalFilePath.Text;
            string remoteFilePath = txtRemoteFilePath.Text;

            if (string.IsNullOrWhiteSpace(host) || string.IsNullOrWhiteSpace(username) ||
                string.IsNullOrWhiteSpace(localFilePath) || string.IsNullOrWhiteSpace(remoteFilePath))
            {
                lblStatus.Text = "Please fill in all required fields.";
                lblStatus.ForeColor = System.Drawing.Color.Red;
                return;
            }

            if (!File.Exists(localFilePath))
            {
                lblStatus.Text = "Local file not found.";
                lblStatus.ForeColor = System.Drawing.Color.Red;
                return;
            }

            try
            {
                using (SftpClient sftpClient = new SftpClient(host, username, password))
                {
                    await Task.Run(() => sftpClient.Connect());
                    lblStatus.Text = "Connected to SFTP server.";

                    using (var fileStream = new FileStream(localFilePath, FileMode.Open))
                    {
                        await Task.Run(() => sftpClient.UploadFile(fileStream, remoteFilePath));
                    }

                    lblStatus.Text = "File transferred successfully!";
                    lblStatus.ForeColor = System.Drawing.Color.Green;
                }
            }
            catch (Renci.SshNet.Common.SshAuthenticationException authEx)
            {
                lblStatus.Text = "Authentication failed: " + authEx.Message;
                lblStatus.ForeColor = System.Drawing.Color.Red;
            }
            catch (Renci.SshNet.Common.SshConnectionException connEx)
            {
                lblStatus.Text = "Connection failed: " + connEx.Message;
                lblStatus.ForeColor = System.Drawing.Color.Red;
            }
            catch (Exception ex)
            {
                lblStatus.Text = "An error occurred: " + ex.Message;
                lblStatus.ForeColor = System.Drawing.Color.Red;
            }
        }
    }
}

C# code for SFTP file transfer logic in Form1.cs

Running and Testing the Application

Once the code is in place, you can build and run your application. Ensure you have access to an SFTP server for testing. Many hosting providers offer SFTP access, or you can set up a local SFTP server for development purposes.

1. Build the Project

In Visual Studio, go to Build > Build Solution to compile your application.

2. Run the Application

Press F5 or click the Start Debugging button to launch your WinForms application.

3. Enter SFTP Details

Input your SFTP server's host, username, and password into the respective text boxes.

4. Select Local File

Click the 'Browse' button to select a file from your local machine that you wish to upload.

5. Specify Remote Path

Enter the full path on the SFTP server where you want the file to be saved (e.g., /home/user/uploads/my_file.txt).

6. Initiate Transfer

Click the 'Transfer' button. Observe the status label for connection and transfer progress. If successful, the file should appear on your SFTP server.