C # - FtpWebRequest - Multiple requests on the same connection / login

I want to loop around the FTP folder to check if the file arrived

I do:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080"); request.Credentials = new NetworkCredential("anonymous", ""); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; while(true) { using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) { Console.WriteLine(reader.ReadToEnd()); reader.Close(); response.Close(); } } 

But in the second iteration, I get an exception:

Unable to read stream

+5
source share
2 answers

Sorry, I missed this, you only issue one request and try to get a response several times. Try using the code below:

 while(true) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080"); request.Credentials = new NetworkCredential("anonymous", ""); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) { Console.WriteLine(reader.ReadToEnd()); reader.Close(); response.Close(); } } 

You should add some pause at the end of each cycle. You do not want to bombard the server.

+3
source

You cannot reuse an instance of FtpWebRequest for multiple requests.

But since FtpWebRequest runs on top of the connection pool, it can actually reuse the underlying FTP connection. As long as FtpWebRequest.KeepAlive set, the default value is true .

If KeepAlive set to true , the underlying FTP connection does not close when the request completes. When you create another instance of FtpWebRequest with the same URL, the connection will be reused.

 while (true) { FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://localhost:8080"); request.Credentials = new NetworkCredential("anonymous", ""); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; // reuse the connection (not necessary, as the true is the default) request.KeepAlive = true; using (FtpWebResponse response = (FtpWebResponse)request.GetResponse()) using (Stream responseStream = response.GetResponseStream()) using (StreamReader reader = new StreamReader(responseStream)) { Console.WriteLine(reader.ReadToEnd()); reader.Close(); response.Close(); } } 
+3
source

All Articles