Closing interrupted FtpWebRequest

Hi all,

Here is my question:

How can determine if I've lost connection with the server through a FtpWebRequest?

My FTP client is nearly done, but I'm experimenting with my client in the following ways:

  1. Disabling the internet adapter while a file is being downloaded.
  2. Stopping vsftpd instance on the server while a file is being downloaded.

The issue is my FTP client never results in a timeout, it just stagnates forever. Even though I've specifically assigned 5000 ms to the Timeout, and ReadWriteTimeout parameter.

Here is some code setting up the Async FtpWebRequest:

protected FtpWebRequest CreateRequest (string url, string method) { FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address); request.ServicePoint.ConnectionLimit = 100; request.KeepAlive = false; request.UseBinary = true; request.EnableSsl = true; request.UseBinary = true; request.UsePassive = true; request.Timeout = Timeout; request.ReadWriteTimeout =Timeout; request.Method = method; request.Credentials = new NetworkCredential(Username, Password); return request; } 

I am starting the Async download using:

asyncResult = activeRequest.BeginGetResponse(new AsyncCallback(AsyncResponse), activeRequest) 

Here is my async download code:

private void AsyncResponse(IAsyncResult asyncResult) { FtpWebRequest request = (FtpWebRequest)asyncResult.AsyncState; FtpWebResponse response = null; Stream stream = null; try { response = (FtpWebResponse)request.EndGetResponse(asyncResult); if (response == null) return; stream = response.GetResponseStream(); byte[] buffer = new byte[2048]; int bytesRead = 0; fileWriter = new FileStream(path, FileMode.Create, FileAccess.Write); while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { fileWriter.Write(buffer, 0, bytesRead); bytesDownloaded += bytesRead; percent = bytesDownloaded / (float)fileSize; } stream.Close(); fileWriter.Close(); success = true; error = FTPError.None; response.Close(); } catch (WebException exception) { Debug.Log("FTP log: Caught FTP exception\n" + exception); if (stream != null) stream.Close(); // If we were writing bytes to a file, then lets close the stream and delete the file. if (fileWriter != null) { fileWriter.Close(); if (File.Exists(path)) File.Delete(path); fileWriter = null; } response = (FtpWebResponse)exception.Response; if (response != null) { // Determine failure reason. ReadStatusCode(response.StatusCode); response.Close(); } else error = FTPError.Unknown; } } 

The try-catch does work for other FTP exceptions. But it never catches a timeout.

This is using Mono 2.0 in Unity 5.3.41f. Any help would be appreciated.

Thank you.

by derpspacetime via /r/csharp

Leave a Reply