Sunday 4 November 2012

Upload File to FTP Programmatically


Upload File to FTP Programmatically


FTP is a standards based means of transferring files from one location to another. It has been there for moving files across the Internet for quite some time. Microsoft .NET supports FTP with the out of the box implementation of WebClient. When the WebClient sees ftp:// as part of the address it will internally use an FtpWebRequest object to perform the transfer. The following example code demonstrates how to use the WebClient to upload a file to an FTP site. 

static bool UploadFile(string filename)

  {

    string host = @"ftp://[YourFtpServerHere]/";

    string userName = "[username]";

    string password = "[password]";

   

    // Checks for the URL starts from ftp://..

    if (!host.StartsWith("ftp://"))

    {

      host = "ftp://" + host;

    }

 

    Uri uri = new Uri(host);

    FileInfo file = new FileInfo(filename);

    string destinationFilename = host + "/" + file.Name;

 

    try

    {

      WebClient client = new WebClient();

      // Setting the User Credentials

      client.Credentials = new NetworkCredential(userName, password);

      byte[] response = client.UploadFile(destinationFilename, filename);

 

      if (response.Length > 0)

      {

        Console.WriteLine("Response from upload: {0}", Encoding.ASCII.GetString(response));

      }

      return true;

    }

    catch (WebException webEx)

    {

      Console.WriteLine("An exception occurred during the upload: {0}", webEx.Message);

      return false;

    }

  }


With modifying the static void watcher_Created(object sender, FileSystemEventArgs e) event, with:


static void watcher_Created(object sender, FileSystemEventArgs e)

{

         UploadFile(e.name);

}

back to top