Search code examples
c#ftpftpwebrequestftp-client

ftp directory listing timeout. Huge number of subdirs


Is there any way to deal with situation when you need to get list of all directories on a FTP server, where the number of directories is so big that it takes too long to get it and operation fails with timeout?

I wonder if there are some libraries that let you do that somehow?


Solution

  • Try something like this

            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(uri);
            ftpRequest.Credentials = new NetworkCredential("anonymous","[email protected]");//replace with your Creds
            ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
            FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
            StreamReader streamReader = new StreamReader(response.GetResponseStream());
    
            List<string> directories = new List<string>();
    
            string line = streamReader.ReadLine();
            while (!string.IsNullOrEmpty(line))
            {
                directories.Add(line);
                line = streamReader.ReadLine();
            }
    
            streamReader.Close();
    
            // also add some code that will Dispose of the StreamReader object
            // something like ((IDisposable)streanReader).Dispose();
            // Dispose of the List<string> as well 
               line = null;