I have a folder on an SFTP server that has a bunch of files. There are 6 different files, and they are created every 60min. Each with a date and time stamp, and they are held for 3 days.
FilesCodes_Critical.2022-03-17_11-16-22-614.json
FilesCodes_Critical.2022-03-17_12-12-16-818.json
FilesCodes_Critical.2022-03-17_13-11-43-025.json
TransactionAudit.2022-03-14_11-16-23-530.json
TransactionAudit.2022-03-14_12-12-19-764.json
TransactionAudit.2022-03-14_13-11-45-454.json
I am creating a few processes that will run every hour and will pick up a particular file and process it. I know I can use the Name.StartsWith
to grab the correct file, but I can't figure out how to grab the most recent of them. I was thinking that LastWriteTime
could be used, but I can't figure out how to compare it.
fileNamePat = "FileCodes_Critical";
try {
sftpc.Connect();
var files = sftpc.ListDirectory(sFTPPath);
foreach (SftpFile file in files)
{
if (file.Name.StartsWith(fileNamePat))
{
string jsonData = sftpc.ReadAllText(file.FullName);
DataSet ds = JsonConvert.DeserializeObject<DataSet>(jsonData);
}
}
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
I thought of trying something like this to compare and put the final file into targetFile
if (file.Name.StartsWith(fileNamePat))
{
if (file.LastWriteTime > targetFile.LastWriteTime)
{
targetFile = file;
}
}
But I can't figure out where/how to create the SftpFile targetFile
so the comparison will work. I tried SftpFile targetFile = new();
and thought I could check to see if it was blank and then set it, but that doesn't work.
CodePudding user response:
Try using a lambda on your set of files:
foreach (SftpFile file in files.Where(f => f.Name.Contains(fileNamePat))
.OrderByDescending(o => o.LastWriteTime)
.Take(1))
{
[...]
}
Actually you didn't need a for each. you can get your 'target' from lambda:
SftpFile targetFile = files.Where(f => f.Name.Contains(fileNamePat))
.OrderByDescending(o => o.LastWriteTime)
.FirstOrDefault();