Moving a file from one folder to another folder on a ftp site using C#

The following code snippet can be used to move a file from one folder to another folder on an ftp site. I have written this code to answer a question in MSDN forum. It is marked as answered.

I have used System.Net.WebClient object to perform this operation. This class provides common methods for sending data to and receiving data from a resource identified by a URI. The following steps are performed to move a file.

  • Download the source file from ftp location to a folder in local PC.
  • Once the download is completed, uploading the file from local PC to another location on the ftp site.
  • Delete the file from local PC

using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace WinFormTest1
{
  public partial class FtpFileMoveSample : Form
  {
    public FtpFileMoveSample()
    {
       InitializeComponent();
     }

   private void button1_Click(object sender, EventArgs e)
  {
     System.Net.WebClient wc1 = new System.Net.WebClient();
     wc1.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
     System.Uri uri1 = new Uri("ftp://ftpUserId:Password@ftpServerIP/abc.txt");
     wc1.DownloadFileAsync(uri1, @"D:\Temp\abc.txt");
  }

  static void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
  {
     System.Net.WebClient wc2 = new System.Net.WebClient();
     wc2.UploadFileCompleted += new System.Net.UploadFileCompletedEventHandler(wc_UploadFileCompleted);
     System.Uri url2 = new Uri("ftp://ftpUserId:Password@ftpServerIP/Test/xyz.txt");
     wc2.Proxy = null;
     wc2.UploadFileAsync(url2, @"D:\Temp\abc.txt");
  }

  static void wc_UploadFileCompleted(object sender, System.Net.UploadFileCompletedEventArgs e)
  {
     System.IO.File.Delete(@"D:\Temp\abc.txt");
     MessageBox.Show("File has been moved");
   }
 }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: