Not logged in - Login

Sample to upload file via FTP

The following illustrates an example of how to upload a file to an FTP server.

public static void UploadFileToFtp(string sFullFileName, string sFtpServerPath, string sFtpUser, string sFtpPassword)
{
   #region do some parameter validation

   System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(sFullFileName), "Parameter 'sFullFileName' cannot be null");
   System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(sFtpServerPath), "Parameter 'sFtpServerPath' cannot be null");
   System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(sFtpUser), "Parameter 'sFtpUser' cannot be null");
   System.Diagnostics.Contracts.Contract.Requires(!string.IsNullOrWhiteSpace(sFtpPassword), "Parameter 'sFtpPassword' cannot be null");

   #endregion

   try
   {
      // Get the object used to communicate with the server.
      FtpWebRequest request = WebRequest.Create(sFtpServerPath) as FtpWebRequest;
      if (request == null) throw new System.Exception(string.Format("Unable to create web request to FTP, '{0}'", sFtpServerPath));

      //FtpWebRequest request = WebRequest.Create("ftp://www.contoso.com/test.htm") as FtpWebRequest;
      request.Method = WebRequestMethods.Ftp.UploadFile;

      // set the credentials
      request.Credentials = new NetworkCredential(sFtpUser, sFtpPassword);
      //// This example assumes the FTP site uses anonymous logon.
      //request.Credentials = new NetworkCredential("anonymous", "janeDoe@contoso.com");



      byte[] fileContents = null;
      fileContents = System.IO.File.ReadAllBytes(sFullFileName);
      // Copy the contents of the file to the request stream.
      //using (StreamReader sourceStream = new StreamReader(sFullFileName))
      //{
      //   fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
      //   sourceStream.Close();
      //   request.ContentLength = fileContents.Length;
      //}

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


      using (FtpWebResponse response = request.GetResponse() as FtpWebResponse)
      {
         //Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);

         response.Close();
      }


   }
   catch (WebException ex)
   {
      throw new System.Exception(((FtpWebResponse)ex.Response).StatusDescription, ex);
   }

}