FTP Upload fails 'The underlying connection was closed: An unexpected error occurred on a receive.'
Asked Answered
R

1

6

I'm trying to upload files to an FTP, and have been doing so successfully until today. Here (at work) I've never had issues, but in production on-site we have had sporadic issues, but now today all of a sudden it wont work 100% of the time and I can't figure this out for the life of me.

I've tried nearly everything I could find.

  • This is NOT a web service.
  • I have increased my Timeout and ReadWriteTimeout to -1 for the FtpWebRequest.
  • I have set the WriteTimeout and ReadTimeout of the stream I use to write the file contents.
  • We have made sure outbound rules are set to allow the port we're communicating over etc and can confirm we can write/read using FileZilla from the same machine/network.
  • The files are NOT large. They max at 1MB and are simple text files.

Below is the method I use. Let me know if you need anymore information.

private static void FtpUpload(String username, String password, String address, 
                              Int32 port, Boolean usePassive, String filePath)
{
    try
    {
        String fileName = "";

        fileName = Path.GetFileName(filePath);
        FtpWebRequest request = null;
        request = (FtpWebRequest)FtpWebRequest.Create(String.Format("ftp://{0}", address));

        request.Credentials = new NetworkCredential(
            username,
            password);
        request.UsePassive = usePassive;
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.Timeout = -1;
        request.ReadWriteTimeout = -1;
        request.KeepAlive = false;
        request.Proxy = null;

        Console.WriteLine(String.Format("Uploading {0}...", fileName));

        Stream ftpStream = null;

        using (ftpStream = request.GetRequestStream())
        {
            ftpStream.WriteTimeout = -1;
            ftpStream.ReadTimeout = -1;

            using (FileStream file = File.OpenRead(filePath))
            {
                file.CopyTo(ftpStream);
            }
        }
    }
    catch
    {
        throw;
    }            
}

screenshot

EDIT:

This code snippit works. Note when I update this snippet to use using blocks it goes back to failing. Could the use of using block be the cause?

public static void FtpUpload(
    String username, 
    String password, 
    String address, 
    Int32 port, 
    Boolean usePassive, 
    String filePath)
{

    string ftpServerIP = String.Format("ftp://{0}", address);
    string ftpUserID = username;
    string ftpPassword = password;
    FileInfo fileInf = new FileInfo(filePath);

    try
    {

        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerIP);

        request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
        request.Method = WebRequestMethods.Ftp.UploadFile;
        request.UseBinary = false;
        request.UsePassive = false;
        request.ContentLength = fileInf.Length;

        // The buffer size is set to 2kb
        int buffLength = 2048;
        byte[] buff = new byte[buffLength];
        int contentLen;

        FileStream fs = fileInf.OpenRead();

        Stream strm = request.GetRequestStream();

        contentLen = fs.Read(buff, 0, buffLength);

        while (contentLen != 0)
        {
            // Write Content from the file stream to the FTP Upload Stream
            strm.Write(buff, 0, contentLen);
            contentLen = fs.Read(buff, 0, buffLength);
        }

        strm.Close();
        fs.Close();

    }
    catch
    {
        throw;
    }
}
Relieve answered 3/9, 2015 at 18:43 Comment(6)
I checked your code and it did work for me. Did you set usePassive=true. This may be a reason for your exception (see SO Question )Hackett
This is the problem, it works but under a particular environment it does not and it doesn't appear to be the firewall. And yes I have tried both true and false for usePassive.Relieve
Here's a twist, I took my code and isolated it. It behaved just as it did in the original project, worked w/ dev. environment, failed w/ prod. environment. NOW I found this example/solution http://www.experts-exchange.com/questions/28693905/FtpWebRequest-The-underlying-connection-as-closed-An-unexpected-error-has-occurred-on-a-receive.html took it and it works both here and there.. I don't get what I'm missing.Relieve
most examples that i know and found did use some kind of Write(...) (MSDN) method on the stream - instead of copy(..)Hackett
I was to previously until this started. Both when I used write or copy yielded the same behavior.Relieve
I was having the same issue and found that the file was successfully uploaded to the server, so the connection wasn't closed before completing the upload process. A wireshark capture shows no issues related with the connection itself, it just seems to throw a webexception on success. As noted, sending blocks works 100% of the time.Crofter
C
3

For anyone else who stumbles across this, the solution contained in

http://www.experts-exchange.com/questions/28693905/FtpWebRequest-The-underlying-connection-as-closed-An-unexpected-error-has-occurred-on-a-receive.html

worked for me, you had to set the following to false

var request = (FtpWebRequest)WebRequest.Create(finalPath);
request.UseBinary = false;
request.UsePassive = false;

This solved the problem of the FTP upload working locally and failing once deployed to UAT

Cymose answered 26/6, 2020 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.