0

I have code what gets a content of some FTP directory. At some servers I've tested it works fine.

But at one server this method throws an exception when we try to get response.

public static List<string> ListDirectory(string dirPath, string ftpUser, string ftpPassword)
    {
        List<string> res = new List<string>();

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
        request.KeepAlive = false;

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        while (!reader.EndOfStream)
        {
            res.Add(reader.ReadLine());
        }
        reader.Close();
        response.Close();

        return res;
    }

At catch section I have something like this

catch (WebException e)
{
   FtpWebResponse response = (FtpWebResponse)e.Response;
   /*in my case response.Status = ActionNotTakenFileUnavailableOrBusy*/
   ....
}

It works before but now it fails when folder is empty. If there is something there it works. And I can see this directory with TotalCommander.

Any ideas why?

Vitalii
  • 10,091
  • 18
  • 83
  • 151

1 Answers1

0

This is an example on how to get a listing of a remote directory using the free library System.Net.FtpClient available from CodePlex.
I have used it in many occasions and, in my opinion, is more easy to work with

public void GetListing() 
{
    using (FtpClient conn = new FtpClient()) 
    {
        conn.Host = "your_ftp_site_url";
        conn.Credentials = new NetworkCredential("your_user_account", "your_user_password");
        foreach (FtpListItem item in conn.GetListing(conn.GetWorkingDirectory(),  FtpListOption.Modify | FtpListOption.Size)) 
        {
              switch (item.Type) 
              {
                    case FtpFileSystemObjectType.Directory:
                        Console.WriteLine("Folder:" + item.Name);
                        break;
                    case FtpFileSystemObjectType.File:
                        Console.WriteLine("File:" + item.Name);
                        break;
            }
        }
    }
}

You can find the download from this pages

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Unfortunately I have exception that "path is correct but no answer". It seems that the same issue as before – Vitalii Apr 30 '13 at 15:52