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:

string ConnectionString = "ftp://" + strFTPServer + ':' + intFTPPort + "/" + strFtpDirectory + @FileName;

FtpWebRequest FtpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString);
FtpRequest.Credentials = new NetworkCredential(strUsername, strPassword);
FtpRequest.KeepAlive = false;

Now we are ready to delete the file:

FtpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
FtpRequest.GetResponse().Close();

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:

string ConnectionString = "ftp://" + strFTPServer + ':' + intFTPPort + "/" + strFtpDirectory + @FileName;

FtpWebRequest FtpRequest = (FtpWebRequest)FtpWebRequest.Create(ConnectionString);
FtpRequest.Credentials = new NetworkCredential(strUsername, strPassword);
FtpRequest.KeepAlive = false;

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

FtpRequest.Method = WebRequestMethods.Ftp.Rename;
FtpRequest.RenameTo = NewFileName;
FtpRequest.GetResponse().Close();

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.

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.