File Upload Using FtpWebRequest In C#

This snippet shows how to upload a file to an ftp server using the FtpWebRequest Class.


  1. using System;
  2. using System.IO;
  3. using System.Net;
  4. class Program
  5. {
  6.     static void Main(string[] args)
  7.     {
  8.         string FTPAddress = "";
  9.         string filename = "samplefile.txt";
  10.         string username = "";
  11.         string password = "";
  12.         try
  13.         {
  14.             FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("ftp://"
  15.             + FTPAddress +"/samplefile.txt");
  16.             request.Method = WebRequestMethods.Ftp.UploadFile;
  17.             request.Credentials = new NetworkCredential(username, password);
  18.             request.UsePassive = true;
  19.             request.UseBinary = true;
  20.             request.KeepAlive = false;
  21.             FileStream stream = File.OpenRead(filename);
  22.             byte[] buffer = new byte[stream.Length];
  23.             stream.Read(buffer, 0, buffer.Length);
  24.             stream.Close();
  25.             Stream reqStream = request.GetRequestStream();
  26.             reqStream.Write(buffer, 0, buffer.Length);
  27.             reqStream.Close();
  28.             Console.WriteLine("Upload Complete");
  29.         }
  30.         catch (WebException e)
  31.         {
  32.             Console.WriteLine(e.Message);
  33.         }
  34.         Console.ReadKey();
  35.     }
  36. }

No comments:

Post a Comment