How to write api method to Read file and save it in ftp server using webapi c#

[Route("getdata")]
        [HttpPost]
        public string ReadFromAzureAS(string path)
        {
            //FTP Server URL.
            string ftp = "ftp://localhost:21/";

            //FTP Folder name. Leave blank if you want to upload to root folder.
            string ftpFolder = "Uploads/";

            string status = "File Transfer Failed";

            FileStream stream = File.OpenRead(path);
            byte[] fileBytes = new byte[stream.Length];

            stream.Read(fileBytes, 0, fileBytes.Length);
            stream.Close();
            //Begins the process of writing the byte array back to a file
            string fileName = Path.GetFileName(path);           

            try
            {
                //Create FTP Request.
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp + ftpFolder + fileName);
                request.Method = WebRequestMethods.Ftp.UploadFile;

                //Enter FTP Server credentials.
                request.Credentials = new NetworkCredential("testuser", "123456789");
                request.ContentLength = fileBytes.Length;
                request.UsePassive = true;
                request.UseBinary = true;
                request.ServicePoint.ConnectionLimit = fileBytes.Length;
                request.EnableSsl = false;

                using (Stream requestStream = request.GetRequestStream())
                {
                    requestStream.Write(fileBytes, 0, fileBytes.Length);
                    requestStream.Close();
                }

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

                
                response.Close();
                status = "File Transfer success";
            }
            catch (WebException ex)
            {
                throw new Exception((ex.Response as FtpWebResponse).StatusDescription);
            }
            return status;
        }

Comments

Popular posts from this blog

Implement virtualisation in kendo drop down list using jquery ajax in mvc, aspx page

How to Create trigger to Update the NoofOrgs Count under each category in Category Table based on Temp Table in Sql Server

How to Preview the image and download which is in base64string format in mvc view using C#