开发者

How to download FTP Files from Previous date to Current Date

I can download ftp files from C# but it downloads the current date file. I need to download the files from previous date to current date. For example, my files are:

xys04-02-2011.zip xys04-03-2011.zip xys04-04-2011.zip

I am trying the following code in console application:

string defaultLocalFolder_MCX = "C:\\";

FastZip fzMCX = new FastZip();

fzMCX.ExtractZip(
    defaultLocalFolder_MCX + "\\xys03-31-2011.zip", 
    defaultLocalFolder_MCX, "");

FtpWebRequest requestFileDownload = 
    (FtpWebRequest)WebRequest.Create("ftp://localhost/Source/" + fileName);
requestFileDownload.Credentials = new NetworkCredential("test", "test")开发者_Go百科;
requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;

FtpWebResponse responseFileDownload = 
    (FtpWebResponse)requestFileDownload.GetResponse();

Stream responseStream = responseFileDownload.GetResponseStream();
FileStream writeStream = new FileStream(localPath + fileName, FileMode.Create);

int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);

while (bytesRead > 0)
{
    writeStream.Write(buffer, 0, bytesRead);
    bytesRead = responseStream.Read(buffer, 0, Length);
}

responseStream.Close();
writeStream.Close();

requestFileDownload = null;
responseFileDownload = null;


Well, it sounds like you need to parameterize your method by date, and then generate the filename from that date:

string formattedDate = date.ToString("MM-dd-yyyy", CultureInfo.InvariantCulture);
fzMCX.ExtractZip(
    defaultLocalFolder_MCX + "\\xys" + formattedDate + ".zip", 
    defaultLocalFolder_MCX, "");

Then just call the method in a loop:

for (DateTime date = startDate; date <= dateTime.endDate; date = date.AddDays(1))
{
    FetchZipFile(date);
}

(I just guessed at the name as it's not really clear what's going on with the zip file extraction.)

A few suggestions in terms of code style:

  • Use using statements for all disposable resources, rather than closing them manually. The includes WebResponses.
  • Be consistent in your variable naming; typically local variables are named in camelCase rather than PascalCase
  • Consider extracting the "copy one stream to another" code to a helper method - or if you're using .NET 4, use Stream.CopyTo
  • You don't need to set local variables to null at the end of the method; it's pointless and just creates noise in your source code.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜