Saturday, 17 March 2018

How to delete file from FTP using c#

Description : In this post how to delete file from FTP server using c#

private string DeleteFileFromFTP(string fileName)   
{   
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/" + fileName);   
    request.Method = WebRequestMethods.Ftp.DeleteFile;   
    request.Credentials = new NetworkCredential("username", "password");   
       
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())   
    {   
        return response.StatusDescription;       
    }   
}

- Above code is delete file from FTP in the code WebRequestMethods is "DeleteFile". when file delete from FTP server it return response and description is "250 File deleted successfully"

How to get all file and directory from FTP server using c#

Description : In this post FTP server return all files and directory in response uing c#

private List GetAllFilesnDirectory() 

    try 
    { 
         FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/"); 
         request.Method = WebRequestMethods.Ftp.ListDirectory; 
 
         request.Credentials = new NetworkCredential("username", "password"); 
         FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 
         Stream responseStream = response.GetResponseStream(); 
         StreamReader reader = new StreamReader(responseStream); 
         string names = reader.ReadToEnd(); 
 
         reader.Close(); 
         response.Close(); 
 
         return names.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList(); 
    } 
    catch (Exception) 
    { 
        throw; 
    } 
}

- Above code return ListDirectory from FTP response and get in stream than parse response and get list of files and directory