3

I'm trying to get into C# programming, but for some reason I'm stuck with trying to count all files that are uploaded on my ftp server. I already tried some code from stackoverflow

Code:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(server);
request.Method = WebRequestMethods.Ftp.ListDirectory;

request.Credentials = new NetworkCredential(user, password);
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string names = reader.ReadToEnd();

reader.Close();
response.Close();

return names.Split(
    new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).ToList();

He does connect to the server but just shows me there in only one file that he could find.

Here you can see the list as a string:

There is the file which he found:

All files that are uploaded on my server:

Here is my list (I don't understand why there are so many indexes):

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Florian Zaskoku
  • 477
  • 3
  • 13

1 Answers1

1

Your code works for me, but @Ozug can be right that your server fails to use CRLF line endings.

A more robust (and more efficient too) implementation is:

List<string> names = new List<string>();
while (!reader.EndOfStream)
{
    names.Add(reader.ReadLine());
}

It should handle even CR line endings.

See also C# class to parse WebRequestMethods.Ftp.ListDirectoryDetails FTP response.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992