while (!isStop)
{
isStop = FTPManager.DownloadFile(fileName);
// Set the Interval to 5 minutes.
System.Threading.Thread.Sleep(300000);
}
}
public class FTPManager
{
public static bool DownloadFile(string fileName)
{
bool isStop = false;
try
{
LogManager.Instance.LogInformation("Connecting To FTP Server...");
FtpWebRequest request = WebRequest.Create(string.Format("{0}/{1}",
Configuration.FTPServer, fileName)) as FtpWebRequest;
request.Method = "RETR";
request.Credentials = new NetworkCredential(Configuration.FTPUser, Configuration.FTPPassword);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
using (WebResponse response = request.GetResponse() as FtpWebResponse)
{
LogManager.Instance.LogInformation(string.Format("Downloading File {0}... ", fileName));
using (MemoryStream memStream = new MemoryStream())
{
using (Stream responseStream = response.GetResponseStream())
{
byte[] buffer = new byte[0x400];
int readBytes = 0;
while ((readBytes = responseStream.Read(buffer, 0, buffer.Length)) != 0)
memStream.Write(buffer, 0, readBytes);
}
using (FileStream fileStream = new FileStream(string.Format(@"{0}\{1}", Configuration.DownloadDirectory, fileName), FileMode.Create))
{
memStream.WriteTo(fileStream);
isStop = true;
}
LogManager.Instance.LogInformation(string.Format("File {0} Downloaded Successfully.", fileName));
}
}
//LogManager.Dispose();
}
catch (WebException wex)
{
FtpWebResponse response = wex.Response as FtpWebResponse;
if (response != null)
{
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)//判断FTP上是否存在该文件
LogManager.Instance.LogInformation(string.Format("File '{0}' Not Found On FTP.", fileName));
else
LogManager.Instance.LogException(wex);
}
}
catch (Exception exception)
{
LogManager.Instance.LogException(exception);
}
return isStop;
}
}