I have a C# program that checks a ftp directory for new files every x seconds. If a new file is found it is downloaded. That works fine. If I start the program without running the ftp server the program loops and returns a message that the server cannot be reached. Then I start the server and the program connects as it should. But if I quit the ftp server again my program gets stuck in the FtpWebResponse.
I have a using statement block in a try catch block to close all connections.
while (true)
{
//...
FtpFileList = null;
while (FtpFileList == null)
{
FtpFileList = await GetFtpFileList(adress, user, password);
await Task.Delay(3000);
}
await Task.Delay(27000);
//...
}
public static async Task<List<string>> GetFtpFileList(string address, string user, string password)
{
try
{
List<string> returnValue = new List<string>();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.Credentials = new NetworkCredential(user, password);
using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync()) //The program gets stuck here
{
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (reader.Peek() >= 0)
{
returnValue.Add(reader.ReadLine());
}
}
AddToLogFile(DateTime.Now + ": " + "FTP directory updated");
return returnValue;
}
catch (WebException e)
{
AddToLogFile(DateTime.Now + ": " + e.Message);
return null;
}
}
I expect the program to reconnect to the server after the connection was lost but instead it gets stuck.
Any help and hints how to solve that issue is appreciated.
Just to let you know I solved the issue by implementing a workaround: Instead of using await request.GetResponseAsync()
I use the normal GetResponse() method in another thread which works without any problems so far: await Task.Run(() => request.GetResponse())