I'm trying to get a list of the files on an FTP server, then one by one check if that file exists on the local system and if it does compare the dates modified and if the ftp file is newer download it.
private void btnGo_Click(object sender, EventArgs e)
{
string[] files = GetFileList();
foreach (string file in files)
{
if (file.Length >= 5)
{
string uri = "ftp://" + ftpServerIP + "/" + remoteDirectory + "/" + file;
Uri serverUri = new Uri(uri);
CheckFile(file);
}
}
this.Close();
}
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
WebResponse response = null;
StreamReader reader = null;
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + remoteDirectory));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
reqFTP.Proxy = null;
reqFTP.KeepAlive = false;
reqFTP.UsePassive = false;
response = reqFTP.GetResponse();
reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
return result.ToString().Split('\n');
}
catch
{
if (reader != null)
{
reader.Close();
}
if (response != null)
{
response.Close();
}
downloadFiles = null;
return downloadFiles;
}
}
private void CheckFile(string file)
{
string dFile = file;
string[] splitDownloadFile = Regex.Split(dFile, " ");
string fSize = splitDownloadFile[13];
string fMonth = splitDownloadFile[14];
string fDate = splitDownloadFile[15];
string fTime = splitDownloadFile[16];
string fName = splitDownloadFile[17];
string dateModified = fDate + "/" + fMonth+ "/" + fYear;
DateTime lastModifiedDF = Convert.ToDateTime(dateModified);
string[] filePaths = Directory.GetFiles(localDirectory);
// if there is a file in filePaths that is the same as on the server compare them and then download if file on server is newer
foreach (string ff in filePaths)
{
string[] splitFile = Regex.Split(ff, @"\\");
string fileName = splitFile[2];
FileInfo fouFile = new FileInfo(ff);
DateTime lastChangedFF = fouFile.LastAccessTime;
if (lastModifiedDF > lastChangedFF) Download(fileName);
}
}
In the check file method, for each file (they are .exe files) I keep getting different results when I split the string i.e. for one file the file name was at column 18 another it was at 16 etc. I also can't always get the year portion of the file.