Search code examples
c#.netftpftpwebrequestftps

C# FTPS freeze/timeout when connecting to port 990


I'm trying to upload files to an FTPS fileshare. But I can't get the code to work. When the code below starts the program just hangs, without any errors. Eventually there will come a timeout error that says system error. I've tried many things, also library's etc. Does anyone have experience with an FTPS upload? This code works with a normal FTP I've tried.

var ftpServerIP = "Ftp.company1.company2.nl:990";
var ftpUserID = "Username";
var ftpPassword = "Password";

FileInfo fileInf = new FileInfo(@"D:\testfile.txt");
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri provided
reqFTP =
    (FtpWebRequest)FtpWebRequest.Create(
        new Uri("ftp://" + ftpServerIP + "/IDEE_MOX/" + fileInf.Name));
reqFTP.EnableSsl = true;

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;

reqFTP.ContentLength = fileInf.Length;

int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

FileStream fs = fileInf.OpenRead();

try
{
    Stream strm = reqFTP.GetRequestStream();
    contentLen = fs.Read(buff, 0, buffLength);
    while (contentLen != 0)
    {
        strm.Write(buff, 0, contentLen);
        contentLen = fs.Read(buff, 0, buffLength);
    }
    strm.Close();
    fs.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message, "Upload Error");
}

Does anyone knows what's wrong with this code and why its freezing? I'm kind of stuck here.


Solution

  • The .NET framework (FtpWebRequest) does not support an implicit TLS/SSL. Only explicit, see:
    Does .NET FtpWebRequest Support both Implicit (FTPS) and explicit (FTPES)?

    So, you cannot connect to the port 990 (implicit TLS/SSL).


    Though as your FTP server most likely supports the explicit TLS/SSL too, just use it. You already set the EnableSsl (what is explicit TLS/SSL). So just connect to the default port 21 and it's done:

    var ftpServerIP = "Ftp.company1.company2.nl"; 
    

    (no explicit port needs to be specified, as the 21 is the default)


    In rare situation that your server does not support the explicit TLS/SSL, you need to use a 3rd party FTP client library. Some are mentioned in the question linked above. My WinSCP .NET assembly supports the implicit FTPS too. As you have already made the connection working with WinSCP GUI, using the implicit TLS/SSL, you can have a code template generated.