Uploading files to FTP server using ASP.Net

Uploading files using FileUpload server control is very common and easy with ASP.Net. But normally in this method files are uploaded to the hard disk of the web server. Here are few articles on this:

But what if we want to upload the files directly to some FTP server instead of web server. This article show how to use same FileUpload server control of ASP.Net to upload files directly to some other FTP server.

Below is the function written in C# which takes HttpPostedFile object as parameters and uploads the associated file to FTP server ftp://demo.myFtpServer.com/UploadFles

 

 

private bool UploadToFTP(HttpPostedFile fileToUpload)
       {

           try
           {
               string uploadUrl = @"ftp://demo.myFtpServer.com/UploadFles";
               string uploadFileName = fileToUpload.FileName;

               Stream streamObj = fileToUpload.InputStream;
               Byte[] buffer = new Byte[fileToUpload.ContentLength];
               streamObj.Read(buffer, 0, buffer.Length);
               streamObj.Close();
               streamObj = null;

               string ftpUrl = string.Format("{0}/{1}", uploadUrl, uploadFileName);
               FtpWebRequest requestObj = FtpWebRequest.Create(ftpUrl) as FtpWebRequest;
               requestObj.Method = WebRequestMethods.Ftp.UploadFile;
               requestObj.Credentials = new NetworkCredential("userid", "password");
               Stream requestStream = requestObj.GetRequestStream();
               requestStream.Write(buffer, 0, buffer.Length);
               requestStream.Flush();
               requestStream.Close();
               requestObj = null;

               return true;
           }
           catch
           {
               return false;
           }
       }

Additional links: