I have a connection routine that attempts to connect to the ftp server. I have a decent handle on that. My issue is that it only catches exceptions during the connection. I need to watch the connection and catch anything that might happen afterwards.
This is part of a MUCH larger program, the gist is that the main program does a bunch of processing and puts files into a folder. It connects to the FTP server, moves files to and from and then processes them.
My thought is to create a thread after successful connection that would stay active and monitor the connection.
Here is what I have....
static public void sftpConnect()
{
int trymax = 10;
int trycount = 1;
int connectDelay = 0;
Random rnd = new();
while (trycount <= trymax)
{
try
{
sFTPFiles = new();
sftpc = new(Config.sFTPServer, Config.sFTPServerPort, Config.sFTPServerUID, Config.sFTPServerPWD);
Logging.Log(Logging.LogLevel.Info, new string[] { $"Connection Attempt: {trycount}" });
Console.WriteLine($"Connection Attempt: {trycount}");
sftpc.Connect();
if (sftpc.IsConnected)
{
Logging.Log(Logging.LogLevel.Notice, new string[] { $"Successfully Connected to sFTP Server at '{DateTime.Now}" });
Console.WriteLine($"Successfully Connected to sFTP Server at '{DateTime.Now}");
trycount = 11;
}
}
catch (Exception ex)
{
if (trycount >= trymax)
{
Logging.Log(Logging.LogLevel.Critical, new string[] { $"Exceeded Max Attempts. Refresh Required" });
Console.WriteLine($"Exceeded Max Attempts. Refresh Required");
return;
}
else
{
Logging.Log(Logging.LogLevel.Error, new string[] { $"[Reconnect]: Exception Occured at {DateTime.Now}: {ex.Message}. Will attempt to reconnect." });
Console.WriteLine($"[Reconnect]: Exception Occured at {DateTime.Now}: {ex.Message}. Will attempt to reconnect.");
trycount++;
connectDelay = rnd.Next(5000, 10000);
Thread.Sleep(connectDelay);
continue;
}
}
}
}
What I have tried:
I'm thinking of something like this for the listener, but I'm not good with threads, so I don't know how to create a thread that would monitor and reconnect, and not create a spaghetti mess of threads.
static public void sftpListener(sftpClient sftpc)
{
while (sftpc.IsConnected)
{
try
{
}
catch (Exception ex)
{
if (!sftpc.IsConnected)
sftpConnect();
}
}
}