I am really struggling in finding out how to make an automatic daily download of SFTP files from a website. What I want to do is to set up a time in the day that automatically downloads the most recent file from the website and store it in my computer documents.
I found the code below but it is not working. First, I do not really understand what remoteDirectory stands for and if I really need to use it. Second, in the file.name I am not sure what name to put because the file name in the website varies a little from
each other because of the date.
*Note that I have activated the background worker (really don't know if necessary to use)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Renci.SshNet;
using Renci.SshNet.Sftp;
using System.Threading;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Downloading started");
Thread.Sleep(1000);
backgroundWorker1.RunWorkerAsync();
Thread.Sleep(1000);
}
private void listFiles()
{
string host = "WebsiteThatINeed.com";
string username = "TheUsernameToLoginToWebsite";
string password = "PasswordToLoginTOWebsite";
double count = 0;
string remoteDirectory = "xxxxxxxxx"; //don't know what it means or what to put
using (SftpClient sftp = new SftpClient(host, username, password))
{
try
{
sftp.Connect();
var files = sftp.ListDirectory(remoteDirectory);
foreach(var file in files)
{
count = count + 1;
if ((file.Name != ".") && (file.Name !=". ."))
{
if(file.Name.Contains("same word document but different date")) //Is this how I should put the website file name?
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), file.Name);
using (Stream fileStream = File.OpenWrite(path))
{
sftp.DownloadFile(remoteDirectory + "/" + file.Name, FileStream);
}
}
double percentage = (count / files.Count()) * 100;
backgroundWorker1.ReportProgress((int)percentage);
}
}
}
}