我试图获得FTP服务器上的文件列表,然后逐个检查该文件是否存在于本地系统上,以及它是否比较了修改日期和如果ftp文件较新,请下载它。从FTP服务器下载新文件和修改后的文件
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);
}
}
在检查文件的方法,对每个文件(它们是.exe文件)我不断收到不同的结果,当我分割字符串即一个文件的文件名是在第18栏另一个是在16等。我也不能总是得到文件的年份。
这是一个馊主意。我尝试了ftplib和ftps,两者都不稳定,因为它们间歇性地抛出异常。即使我将呼叫置于5次重试循环中,仍然无法使其可靠工作。 ftplib会抛出无法在主线程中捕获的异常,从而使我的Windows服务每隔一小时左右崩溃。我不能说netftp,因为我没有尝试它。我最终使用标准的.NET FtpWebRequest类和非标准的IIS配置(通过端口21的ftps)来使它工作。我最终使用ftplib的解析器来获取目录列表详细信息。 – NightOwl888 2012-12-02 10:12:09