3

I had created folders in FTP server with year, month and date that is after getting logged in to the server we can see a folder created on year when I click on that year it shows month and when I click on month it shows date. Now I need to delete this folder.

Below is my code to delete folder in FTP server

FtpWebResponse responseFileDelete = (FtpWebResponse)ftpRequest.GetResponse();

An unhandled exception of type 'System.Net.WebException' occurred in System.dll
Additional information: The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

Can you please help me out to delete a folder.

1 Answers1

5
  1. The URL you assemble for the DeleteFile call is wrong.

    With:

    path = "ftp://ftp.example.com/" + "/" + ff;
    string server = "ftp://ftp.example.com/";
    

    The ftpURL + "/" + ftpDirectory is ftp://ftp.example.com/ftp://ftp.example.com//dir while you want ftp://ftp.example.com//dir or maybe ftp://ftp.example.com/dir.

    Use just the ftpDirectory

    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpDirectory);
    
  1. You cannot delete a folder with the WebRequestMethods.Ftp.DeleteFile anyway. You have to use the WebRequestMethods.Ftp.RemoveDirectory.

    ftpRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
    

    But note that even the .RemoveDirectory can remove an empty directory only.

    You have to recursively delete files and subfolders of the folder first and only then you can delete the folder itself.

    Implementing a recursion using FtpWebRequest is not easy, particularly because it does not support the MLSD command (what is the only reliable way to distinguish files from folders). For details, see my answer to C# Download all files and subdirectories through FTP.


    Alternatively, use another FTP library that supports recursive operations.

    For example with WinSCP .NET assembly, you can use Session.RemoveFiles to delete a folder with its content in a single call:

    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Ftp,
        HostName = "ftp.example.com",
        UserName = "username",
        Password = "mypassword",
    };
    
    using (Session session = new Session())
    {
        session.Open(sessionOptions);
        session.RemoveFiles("/" + ff);
    }
    

    (I'm the author of WinSCP)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992