Good day all
I have a recon windows service which will download a file which is posted on a ftp site each morning.
At the moment i am listing the directory, getting the last file , an process that file. This method seems a bit resource intensive as i have to add all the files to an array and a file could have an old files name but its the latest file.
Basically what happens is the files will have extensions from 000 to 999. After 999 it will go back to 000.
I am scared that that 000 file won't be the last in the directory listing.
Here is the code i have currently.(Which works, but a bit resource intensive)
StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
string fileName3 = streamReader.ReadLine();
while (fileName3 != null)
{
dirListing.Add(fileName3);
fileName3 = streamReader.ReadLine();
}
request = null;
streamReader = null;
var filetodl = (from i in db.Recons
where i.Extension.Equals(dirListing[dirListing.Count - 1].Split('.')[1])
select i.Extension).FirstOrDefault();
try
{
if (filetodl == null)
{
FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(ftpServer + "/" + filetodl.ToString());
requestFileDownload.Credentials = new NetworkCredential(Username, Password);
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
if (dirListing[dirListing.Count - 1] != null)
{
FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
string FileName = dirListing[dirListing.Count - 1].ToString();
Stream responseStream = responseFileDownload.GetResponseStream();
// Convert to Bytes, and input into DB.
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
bytesRead = responseStream.Read(buffer, 0, Length);
}
// Saves data into the database.
var res = (from r in db.Recons
where r.Extension.Equals(FileName.Split('.')[1])
select r.Extension
).FirstOrDefault();
if (res == null)
{
Recon _recon = new Recon();
_recon.File = buffer;
_recon.Filename = FileName.Split('.')[0];
_recon.ReceivedDate = DateTime.Now;
_recon.Extension = FileName.Split('.')[1];
_recon.isChecked = false;
db.Recons.InsertOnSubmit(_recon);
db.SubmitChanges();
responseStream.Close();
requestFileDownload = null;
responseFileDownload = null;
}
}
}
}
please note i used linq to sql, This might be confusing for some, but its just a normal select statement to check if the file exists in the database , if not , download the file. This select statement might change due to the fact that the file with a same name can be inserted into the database.
Thanks a lot