Search code examples
c#.netftpdirectoryftp-client

How can FTPClient delete a directory?


I want to delete a folder in FTP.

Can FTPClient object delete it?


Solution

  • FtpWebRequest provides the Delete action. Here is a piece of code to achieve that :

                   FtpWebRequest reqFTP = FtpWebRequest.Create(uri);
                    // Credentials and login handling...
    
                    reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
    
                    string result = string.Empty;
                    FtpWebResponse response = reqFTP.GetResponse();
                    long size = response.ContentLength;
                    Stream datastream = response.GetResponseStream();
                    StreamReader sr = new StreamReader(datastream);
                    result = sr.ReadToEnd();
                    sr.Close();
                    datastream.Close();
                    response.Close();
    

    It should work on files and directories. Indeed, please check that you have the right permissions.

    Also, you could not delete folders while they are not empty. You must traverse them recursively to delete content before.

    The exceptions thrown due to right permissions problems are not always very clear...