Search code examples
c#sftpwinscpwinscp-net

How can I download all txt files that has been created in the last 60 seconds from my SFTP Server?


static void Main(string[] args)
{
    var fileSystemWatcher = new FileSystemWatcher(@"filepath")
    {
        Filter = "*.txt",
        NotifyFilter = NotifyFilters.FileName,
        EnableRaisingEvents = true
    };

    fileSystemWatcher.Created += OnActionOccurOnFolderPath;

    Console.ReadLine();
}

public static void OnActionOccurOnFolderPath(object sender, FileSystemEventArgs e)
{
    Console.WriteLine(e.ChangeType);
    Console.WriteLine(e.Name);
    Upload.upload();
}

This uploads any txt file that has been created in a specified path to the SFTP Server.

The server will generate a report about whether the upload and file processing was successful. This usually takes about 2-3 minutes. I then check with a timer every 60 seconds if there has been a new report created.

First I get a list of the files in the directory:

RemoteDirectoryInfo directoryInfo = session.ListDirectory(remotePath);

Here I select the latest file:

RemoteFileInfo latest =
    directoryInfo.Files
        .Where(file => !file.IsDirectory)
        .OrderByDescending(file => file.LastWriteTime)
        .FirstOrDefault();

I go on with downloading the file to check it for some parameters.

session.GetFileToDirectory(latest.FullName, localPath);

But whenever I upload multiple files, there will be multiple reports but I can only download the latest one.

My intention is that I want to download everything that has been created in the last 60 seconds. This needs to be done while the upload of new data can still be assured.

So I suppose that the code above for finding latest need to be changed in some way.


Solution

  • To download files created in the last minute, use file mask time constraint >=60S:

    session.GetFilesToDirectory(remoteDirectory, localDirectory, "*>=60S").Check();