December 29, 2014 by Nitesh

How To Check If a File Exists In FTP Server in C#


In my last post, we saw how can we delete a file from FTP server. However, there might be a situation when you try to delete a file and the file does not exist on the server. In this case, code will throw an error saying “550, File Unavailable“. To solve this, we must know whether a file exists on server before accessing the file. In this post, we will see how can we do the same.

Here’s the code –

        private bool CheckIfFileExistsOnServer(string fileName)
            var request = (FtpWebRequest)WebRequest.Create("" + fileName);
            request.Credentials = new NetworkCredential("username", "password");
            request.Method = WebRequestMethods.Ftp.GetFileSize;

                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                return true;
            catch (WebException ex)
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                    return false;
            return false;

As you see, we create an object of FtpWebRequest class and try to get the FileSize of the requested file. If the file exists, server will return the file size else it will throw an exception saying “File unavailable”. In the catch block, we are catching the exception and checking for the ResponseCode from the response. If the ResponseCode is “ActionNotTakenFileUnavailable“, this means the file is unavailable and we return to the calling method.

Hope you like this post. Keep learning & sharing! Cheers!

#C##Ftp#How To?#Winforms

Support us!

If you like this site please help and make click on any of these buttons!

Powered by WordPress Popup