Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Secure FTP or SFTP using Putty/PSFTP with C# (Open Source) and Task Scheduler Configuration

4.43/5 (7 votes)
29 May 2023CPOL3 min read 31.1K   692  
Simple open source code and technique for SFTP connectivity

Introduction

If you want to use SFTP connection for file transfer, then there are several paid/license tools available in the market and some of them are very tough to work also. So, much complicated coding is required for simple file transfer using those tools.

Recently, one of my clients changed their file transfer server FTP to SFTP and then I did research for a while to find the best way to manage without any paid tool with simple/less C# code. I have used PSFTP with this example.

Now What is PSFTP?

Most of us know about PuTTY. PuTTY is a free SSH, Telnet and Rlogin client for 32-bit Windows systems. PSFTP, the PuTTY SFTP client, is a tool for transferring files securely between computers using an SSH connection.

What You Need for SFTP?

  1. Host Name or FTP Server
  2. User Name
  3. Password

Example: Host Name or FTP Server: ftpdev.mycompany.com
User Name: ftptestuser
Password: ftptestpassword

I will use this information in my coding, however you need to replace it with a valid one.

Let’s Start Now

Please follow the steps given below:

Step 1 (Installing PuTTY)

Download PuTTY and install in your computer (it’s free). It will install at default path C:\Program Files (x86)\PuTTY.

Step 2 (Authorizing PSFTP)

This is a mandatory step, you need to do since it will accept SSH certificate first time from SFTP server. So, this is required before C# coding is done.

Follow either option a or b:

  • Option a: Click on, Windows start button -> All Programs -> PuTTY -> PSFTP
  • Option b: Go to C:\Program Files (x86)\PuTTY, then double click on psftp.exe

You will see a window like:

Image 1

Then try to connect manually.

Command 1: Open ftpdev.mycompany.com

Image 2

Command 2: y

Image 3

Command 3: Enter user name

Image 4

Command 4: Enter password

Image 5

Command 5: You can try some test commands to verify the SFTP files and folder list.

Like Help; quit; ls; get; put, etc. [more can be found at this link].

Background

We need to install PuTTY (free tool) for developing this program, however you do not need any prior experience of PuTTY. You need to just follow the provided instructions.

Using the Code

Create a simple console app in Microsoft Visual Studio.

App.config:

XML
<appSettings>
  <!--psftp path-->
  <add key ="psftp"  value="C:\\Program Files (x86)\\PuTTY\\psftp.exe"/>

  <!--ftp server and credentials-->
  <add key ="user"  value="ftptestuser"/>
  <add key ="pass"  value="ftptestpassword"/>
  <add key ="ftpserver"  value="ftpdev.mycompany.com"/>
</appSettings>

Program.cs:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;
using System.Diagnostics;

namespace PSFTP_Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            /*Example of SFTP using PSFTP */

            /* In this example, the local files are placed in bin/debug folder 
               since I am using AppDomain.CurrentDomain.BaseDirectory path, you can 
               change it but make sure your run time code is accessible to that path.
            */

            /*Send file from local folder to FTP server, send.sftp is a 
              batch file, look the command in the file from the solution            
             */
            PSFTP_TransferFile("send.sftp");
            /*Receive file from FTP server to local folder
              recieve.sftp is a batch file, look the command 
              in the file from the solution            
             */
            PSFTP_TransferFile("recieve.sftp");
            /*delete file from FTP server
              delete.sftp is a batch file, 
              look the command in the file from the solution            
             */
            PSFTP_TransferFile("delete.sftp");
        }
        private static void PSFTP_TransferFile(string batchFile)
        {
            try
            {
                Process myProcess = new Process();
                myProcess.StartInfo.UseShellExecute = true;
                myProcess.StartInfo.FileName = 
                          ConfigurationManager.AppSettings["psftp"].ToString();
                var args1 = ConfigurationManager.AppSettings["user"].ToString() + "@" 
                            + ConfigurationManager.AppSettings["ftpserver"].ToString() + 
                            " -pw " + 
                              ConfigurationManager.AppSettings["pass"].ToString() + 
                            " -batch -be -b " + AppDomain.CurrentDomain.BaseDirectory + 
                            "PSFTP-BatchFile\\" + batchFile;
                myProcess.StartInfo.Arguments = args1;
                myProcess.StartInfo.CreateNoWindow = true;
                var abc = myProcess.Start();
                myProcess.WaitForExit();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error occurred : " + ex.Message);
            }
        }
    }
}

You can also download the complete solution from the link at the top of this article.

How to Configure from Task Scheduler?

Often, we use the SFTP in an automated environment for file transfer. You might find it difficult to run the above application from windows Task Scheduler if you will not configure it properly.

I will provide the steps for configuring in windows task scheduler. Please follow my instructions:

In Windows, go to Start -> Control panel -> Administrative Tools -> Task Scheduler -> then right click on “Task Scheduler Library” -> Create Task.

Step 1: General

Image 6

Step 2: Triggers

Image 7

Step 3: Actions

Image 8

Points of Interest

This article will help you in building SFTP connectivity using PSFTP. You can add more features depending on your requirements.

Your feedback is always welcome.

History

  • 29th May, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)