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

后端 未结 2 874
故里飘歌
故里飘歌 2021-01-12 12:04

I want to loop on a FTP folder for check if a file has arrived

I do:

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(\"ftp://localhost:8080         


        
2条回答
  •  不思量自难忘°
    2021-01-12 13:05

    You cannot reuse the FtpWebRequest instance for multiple requests.

    But as the FtpWebRequest works on top of a connection pool, it actually can reuse an underlying FTP connection. As long as the FtpWebRequest.KeepAlive is set to its default value of true.

    When the KeepAlive is set to true, the underlying FTP connection is not closed, when the request finishes. When you create another instance of the FtpWebRequest with the same URL, the connection is 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();
        }
    }
    

提交回复
热议问题