简体   繁体   中英

Multiple FTP requests - C#

I'm trying to get a listing of files in a specific directory and then I want to check their last modified dates.

Initial request works fine:

FtpWebRequest request;

request = (FtpWebRequest)WebRequest.Create(new Uri(FtpPath));
request.Credentials = new NetworkCredential("username", "password");

request.Method = WebRequestMethods.Ftp.ListDirectory;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

string FileNames = reader.ReadToEnd();

Then after some processing, I pick the files that I'm interested in and attempt to retrieve their time stamps. The following happens in a loop:

request = (FtpWebRequest)WebRequest.Create(new Uri(FtpPath + Files[i]));
request.Credentials = new NetworkCredential("username", "password");

request.Method = WebRequestMethods.Ftp.GetDateTimestamp;

response = (FtpWebResponse)request.GetResponse();
responseStream = response.GetResponseStream();
reader = new StreamReader(responseStream);

FileDates = reader.ReadToEnd();

My FileDates variable never gets set to anything. I'd love to package this in a class to avoid the horrible code duplication but for now I would settle for being able to retrieve the data that I'm interested in.

Here is my rough solution:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(FtpPath));
reuest.Credentials = new NetworkCredential("user", "password");
request.Method = WebRequestMethods.Ftp.ListDirectory;

FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);

string FileNames = reader.ReadToEnd();
string[] Files = Regex.Split(FileNames,"\r\n");

Now I've got an array of all the filenames

Dictionary<string, DateTime> Dates = new Dictionary<string, DateTime>();

for (int i = 0; i <= Files.Length - 1; i++)
{
    request = (FtpWebRequest)WebRequest.Create(new Uri(FtpPath + Files[i]));
    request.Credentials = new NetworkCredential("user", "password");
    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
    response = (FtpWebResponse)request.GetResponse();

    DateTime FileDate = response.LastModified;
    Dates.Add(Files[i], FileDate);
}

And a dictionary that associates a date with each file for further processing. The problem with my initial solution had something to do with the way I was handling the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM