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

How to get the user details, user current level, next level, Rank in sql server

How to update the user level when ever user report any tweet in sql

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