Click here to Skip to main content
15,889,520 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have been facing an issue while downloading file using ftp if i try to download files less than 10MB it's ok but if i download a 12MB file it downloads it till 100% and it
throw Web Exception : "The underlying connection was closed: An unexpected error occurred on a receive"

and after closing streams the file is downloaded correctly on disk !!

i downloaded this file with many tools and it's fine

i have been searching for a long time ago and i found a very huge results about this but guess what .. no answers for the specified case they have answered questions about wcf , web services , etc

Code :

C#
private void FtpDownloadFile(string fileDirectory, string fileName)
        {
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpServerIP + "/" + fileName);

                request.Method = WebRequestMethods.Ftp.GetFileSize;
                request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = true;
                //request.EnableSsl = true;

                intFileSize = request.GetResponse().ContentLength;
                intRunningByteTotal = 0;
                request.ContentLength = intFileSize;

                request = (FtpWebRequest)FtpWebRequest.Create(ftpServerIP + "/" + fileName);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.Credentials = new NetworkCredential(ftpUserID,
                                                            ftpPassword);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;
                //request.EnableSsl = true;
                request.ReadWriteTimeout = 10000000;

                response = (FtpWebResponse)request.GetResponse();
                reader = response.GetResponseStream();

                writer = new FileStream(fileDirectory + "\\" + fileName, FileMode.Create, FileAccess.Write, FileShare.None);
                byte[] byteBuffer = new byte[1024];

                int intByteSize = 0;
                int intProgressPct = 0;

                while ((intByteSize = reader.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
                {
                    try
                    {
                        if (intByteSize == 0)
                        {
                            intProgressPct = 100;
                            FtpDownloadBackground.ReportProgress(intProgressPct);
                        }
                        else
                        {
                            if (reader != null)
                            {
                                writer.Write(byteBuffer, 0, intByteSize);
                            }

                            if (intByteSize + intRunningByteTotal <= intFileSize)
                            {
                                intRunningByteTotal += intByteSize;
                                double dIndex = intRunningByteTotal;
                                double dTotal = byteBuffer.Length;
                                double dProgressPct = 100.0 * intRunningByteTotal / intFileSize;
                                intProgressPct = (int)dProgressPct;
                                totalPercentage = (int)((nDownloadedTotal + intRunningByteTotal) * 100 / totalsize);
                                //------------------------------
                                FtpDownloadBackground.ReportProgress(intProgressPct);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        
                    }
                }
                nDownloadedTotal += intFileSize;
                //------------------------
            }
            catch (WebException ex)
            {
                //Web Exception : "The underlying connection was closed: An unexpected error occurred on a receive"
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.ToString());
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
                if (response != null)
                {
                    response.Close();
                }
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }


thanks in advance
Posted
Updated 15-Jul-12 20:54pm
v4
Comments
Sergey Alexandrovich Kryukov 15-Jul-12 0:50am    
"Downloading ftp file"... Hm. What is "ftp file"? :-)
--SA
Sergey Alexandrovich Kryukov 15-Jul-12 0:53am    
Very bad code, by the way; the major crime is misuse of exception. You can start from reading on what is the exceptions for...
--SA

You Can Try This...

C#
public static bool DownloadFromFTP_FTPS(string remoteFilePath, string localFilePath,string UserId,string Password, out string error)
        {
            error = string.Empty;
            try
            {
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(HostName.TrimEnd(new char[] { '/' }) + "//" + remoteFilePath);
               //request.EnableSsl = true; 
                request.Credentials = new NetworkCredential(UserId, Password);
                request.Method = WebRequestMethods.Ftp.DownloadFile;
                request.UseBinary = true;

                


                // read file into byte array
                StreamWriter requestStream = new StreamWriter(localFilePath);

                Stream sourceStream = request.GetResponse().GetResponseStream();
                byte[] bit = new byte[4096];
                int intSt = sourceStream.Read(bit, 0, bit.Length);

                while (intSt > 0)
                {
                    requestStream.BaseStream.Write(bit, 0, intSt);
                    intSt = sourceStream.Read(bit, 0, bit.Length);
                }

                sourceStream.Dispose();
                requestStream.Dispose();
                requestStream.Close();
                sourceStream.Close();
               

                return true;
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return false;
            }
        }
 
Share this answer
 
Comments
snake1 18-Jul-12 14:43pm    
Thanks for your solution , but i'm still stucked at the same issue

i tried your code and i get the same exception , the problem is i'm able to download 1 - 5MB but when i try to download a 12MB file i get this exception when the file is downloaded and after throwing exception if i close streams or stop debugging the file is downloaded correctly

WebException : The underlying connection was closed: An unexpected error occurred on a receive.
while (intSt > 0) loop
i think the exception has been thrown at this line :
sourceStream.Read(bit, 0, bit.Length);
snake1 18-Jul-12 14:44pm    
the exception is thrown when the file which is 12MB or more is completely downloaded
Hi,

You can download file Asynchronously...

Reference : Click Here
using System;
using System.Net;
using System.Threading;

using System.IO;
namespace Examples.System.Net
{
    public class FtpState
    {
        private ManualResetEvent wait;
        private FtpWebRequest request;
        private string fileName;
        private Exception operationException = null;
        string status;

        public FtpState()
        {
            wait = new ManualResetEvent(false);
        }

        public ManualResetEvent OperationComplete
        {
            get {return wait;}
        }

        public FtpWebRequest Request
        {
            get {return request;}
            set {request = value;}
        }

        public string FileName
        {
            get {return fileName;}
            set {fileName = value;}
        }
        public Exception OperationException
        {
            get {return operationException;}
            set {operationException = value;}
        }
        public string StatusDescription
        {
            get {return status;}
            set {status = value;}
        }
    }
    public class AsynchronousFtpUpLoader
    {  
        // Command line arguments are two strings:
        // 1. The url that is the name of the file being uploaded to the server.
        // 2. The name of the file on the local machine.
        //
        public static void Main(string[] args)
        {
            // Create a Uri instance with the specified URI string.
            // If the URI is not correctly formed, the Uri constructor
            // will throw an exception.
            ManualResetEvent waitObject;

            Uri target = new Uri (args[0]);
            string fileName = args[1];
            FtpState state = new FtpState();
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(target);
            request.Method = WebRequestMethods.Ftp.UploadFile;

            // This example uses anonymous logon.
            // The request is anonymous by default; the credential does not have to be specified. 
            // The example specifies the credential only to
            // control how actions are logged on the server.

            request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");

            // Store the request in the object that we pass into the
            // asynchronous operations.
            state.Request = request;
            state.FileName = fileName;

            // Get the event to wait on.
            waitObject = state.OperationComplete;

            // Asynchronously get the stream for the file contents.
            request.BeginGetRequestStream(
                new AsyncCallback (EndGetStreamCallback), 
                state
            );

            // Block the current thread until all operations are complete.
            waitObject.WaitOne();

            // The operations either completed or threw an exception.
            if (state.OperationException != null)
            {
                throw state.OperationException;
            }
            else
            {
                Console.WriteLine("The operation completed - {0}", state.StatusDescription);
            }
        }
        private static void EndGetStreamCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;

            Stream requestStream = null;
            // End the asynchronous call to get the request stream.
            try
            {
                requestStream = state.Request.EndGetRequestStream(ar);
                // Copy the file contents to the request stream.
                const int bufferLength = 2048;
                byte[] buffer = new byte[bufferLength];
                int count = 0;
                int readBytes = 0;
                FileStream stream = File.OpenRead(state.FileName);
                do
                {
                    readBytes = stream.Read(buffer, 0, bufferLength);
                    requestStream.Write(buffer, 0, readBytes);
                    count += readBytes;
                }
                while (readBytes != 0);
                Console.WriteLine ("Writing {0} bytes to the stream.", count);
                // IMPORTANT: Close the request stream before sending the request.
                requestStream.Close();
                // Asynchronously get the response to the upload request.
                state.Request.BeginGetResponse(
                    new AsyncCallback (EndGetResponseCallback), 
                    state
                );
            } 
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine("Could not get the request stream.");
                state.OperationException = e;
                state.OperationComplete.Set();
                return;
            }

        }

        // The EndGetResponseCallback method  
        // completes a call to BeginGetResponse.
        private static void EndGetResponseCallback(IAsyncResult ar)
        {
            FtpState state = (FtpState) ar.AsyncState;
            FtpWebResponse response = null;
            try 
            {
                response = (FtpWebResponse) state.Request.EndGetResponse(ar);
                response.Close();
                state.StatusDescription = response.StatusDescription;
                // Signal the main application thread that 
                // the operation is complete.
                state.OperationComplete.Set();
            }
            // Return exceptions to the main application thread.
            catch (Exception e)
            {
                Console.WriteLine ("Error getting response.");
                state.OperationException = e;
                state.OperationComplete.Set();
            }
        }
    }
}
 
Share this answer
 
Comments
snake1 19-Jul-12 4:02am    
this code is for uploading file Asynchronously is it available for downloading file Asynchronously?
Suvabrata Roy 19-Jul-12 5:17am    
Just change the code for Downloading as above Or you want I will do the change

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900