Pazartesi, Mart 19, 2018

Download files from FTP with FtpResponse on ASP.NET MVC application

        it woks for large files!
        [HttpGet]   
        public virtual void Download(string g)
        {
         

            Uri uri = (Uri)Session["file_full_path"];


            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
            request.Credentials = new NetworkCredential("username", "password");
            request.UsePassive = true;
            request.UseBinary = true;
            request.EnableSsl = false;

           //find size
            request.Method = WebRequestMethods.Ftp.GetFileSize;

            FtpWebResponse responseSize = (FtpWebResponse)request.GetResponse();
            long size = responseSize.ContentLength;
            responseSize.Close();


            FtpWebRequest request2 = (FtpWebRequest)WebRequest.Create(uri);
            request2.Credentials = new NetworkCredential("username", "password");
            request2.UsePassive = true;
            request2.UseBinary = true;
            request2.EnableSsl = false;

            request2.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse response = (FtpWebResponse)request2.GetResponse();
            Stream dfileResponseStream = response.GetResponseStream();

            Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
            Response.ContentEncoding = System.Text.Encoding.UTF7;
            Response.Charset = "ISO-8859-9";
           
            Response.AddHeader("content-Disposition", "attachment; filename=" + Path.GetFileName(uri.LocalPath));

            while (size > 0)
            {
                if (Response.IsClientConnected)
                {
                    byte[] buffer = new Byte[10000];
                    int length = dfileResponseStream.Read(buffer, 0, 10000);// stream.Read(buffer, 0, 10000);
                    Response.OutputStream.Write(buffer, 0, length);
                    Response.Flush();
                    size = size - length;
                }
                else
                {
                    size = -1;
                }
            }

            response.Close();
         
        }