使用ftpwebrequest下载文件时遇到问题 [英] facing an issue while downloading file using ftpwebrequest

查看:59
本文介绍了使用ftpwebrequest下载文件时遇到问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我尝试下载小于10MB的文件,我在使用ftp下载文件时遇到了问题,但是可以,但是如果我下载12MB的文件,它将下载到100%,并且它
引发Web异常:基础连接已关闭:接收时发生意外错误"

在关闭流之后,文件已正确下载到磁盘上!

我使用许多工具下载了此文件,一切都很好

我很久以前一直在搜索,但我发现了非常不错的结果,但是猜到了什么..对于指定的情况没有答案,他们已经回答了有关wcf,web服务等的问题

代码:

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 :

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

推荐答案

您可以尝试...

You Can Try This...

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;
            }
        }




您可以异步下载文件...

参考:单击此处
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();
            }
        }
    }
}


这篇关于使用ftpwebrequest下载文件时遇到问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆