Expanding the FTP automation

In the previous post I have started the development of FTP automation. The first post did only include some basic functions such as download, upload and list. Now it’s time for some more functionality.

So now let us add the possibility to delete and rename files.

Deleting a file from the FTP server is actually pretty simple. All you have to know is the filename and where it is place. Once you have this information you can use the WebRequestMethods to delete the file.

We will start with making a connection to the FTP Server:

 csharp |  copy code |? 
1
 string ConnectionString = "ftp://" + strFTPServer + ':' + intFTPPort + "/" + strFtpDirectory + @FileName;
2
 
3
FtpWebRequest FtpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString);
4
FtpRequest.Credentials = new NetworkCredential(strUsername, strPassword);
5
FtpRequest.KeepAlive = false;
6

Now we are ready to delete the file:

 csharp |  copy code |? 
1
FtpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
2
FtpRequest.GetResponse().Close();
3

This is done by using WebRequestMethods to set the DeleteFile Method and then afterwards executing the deletion with GetResponse.

Remember to catch Execeptions, to see if the deletion went well.

So now you can delete files from the FTP server.

This was easy. So let us continue with the renaming.

Renaming a file is similar to the deletion of a file. Again all you need to know is the filename & path and then you can use WebRequestMethods to rename the file.

As in the deletion of a file you will start with making the server connection:

 csharp |  copy code |? 
1
string ConnectionString = "ftp://" + strFTPServer + ':' + intFTPPort + "/" + strFtpDirectory + @FileName;
2
 
3
FtpWebRequest FtpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString);
4
FtpRequest.Credentials = new NetworkCredential(strUsername, strPassword);
5
FtpRequest.KeepAlive = false;
6

Now that the server connection is in place – you are ready to perform the renaming:

 csharp |  copy code |? 
1
2
FtpRequest.Method = WebRequestMethods.Ftp.Rename;
3
FtpRequest.RenameTo = NewFileName;
4
FtpRequest.GetResponse().Close();
5

As you can see, we are also here using WebRequestMethods to set Rename Method. First the Method is chosen; you set the new filename with FtpRequest.RenameTo and then afterwards execute the rename with GetResponse.

So the only difference to the deletion is the Method and the RenameTo command.

That’s all folks! Now you can delete and rename files on an Ftp.

You can leave a response, or trackback from your own site.

Leave a Reply


8 × = seventy two