September 19, 2024

Download, Upload,Delete Files from FTP Server Using C#

FTP is a file transfer protocol. We can use it in different ways. Lot of third party software or tools (WinSCP, FireFTP, FileZilla etc) are available for that. Some time we need to perform basic FTP operation in C#. This article describes step by step Download, Upload, Delete ftp in C# . Summary of the article:

  • What is FTP?
  • Show File List of the FTP Server in C#
  • Download File from the FTP Server in C#
  • Upload File from Local Machine to the FTP Server in C#
  • Delete File from the FTP Server in C#
  • Move File from One Directory to Another in the FTP Server in C#
  • Check File Existence in the FTP Server in C#

What is FTP?
File Transfer Protocol or FTP is a standard Internet protocol for transferring files between computers on the network or internet. It is an application protocol. Like others protocol (HTTP, SMTP) FTP uses Internets TCP/IP protocols. FTP is most commonly used to download a file from a server or to upload a file to a server by using network or internet.
We can use FTP with a graphical FTP clients or command line interface or web browser. Different programming language support FTP. Using them we can develop programs to perform some SFT Operations like delete, rename, move, and copy.

Show File List of FTP Server in C#
The following C# code will return the list of all the file names of a FTP Server in a List. For this we need to include the following namespace in the class:

using System.Net;

string _ftpURL = "testftp.com";     //Host URL or address of the FTP server
string _UserName = "admin";         //User Name of the FTP server
string _Password = "admin123";      //Password of the FTP server
string _ftpDirectory = "Receipts";  //The directory in FTP server where the files are present
List F

public List ShowFileList(string ftpURL, string UserName, string Password, string ftpDirectory)
{
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory);
    request.Credentials = new NetworkCredential(UserName, Password);
    request.Method = WebRequestMethods.Ftp.ListDirectory;
    StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream());
    List lines = new List();
    string line;
            
    while ((line = streamReader.ReadLine()) != null)
    {
        lines.Add(line);
    }
    streamReader.Close();
    return lines;
}

Download File from the FTP Server in C#
The following C# code will download all the files from the FTP server into local machine.

string _ftpURL = "testftp.com";             //Host URL or address of the FTP server
string _UserName = "admin";                 //User Name of the FTP server
string _Password = "admin123";              //Password of the FTP server
string _ftpDirectory = "Receipts";          //The directory in FTP server where the files are present
string _FileName = "test1.csv";             //File name, which one will be downloaded
string _LocalDirectory = "D:\\FilePuller";  //Local directory where the files will be downloaded
DownloadFile(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName, _LocalDirectory);

public void DownloadFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName, string LocalDirectory)
{
    if (!File.Exists(LocalDirectory + "/" + FileName))
    {
        try
        {
            FtpWebRequest requestFileDownload = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName);
            requestFileDownload.Credentials = new NetworkCredential(UserName, Password);
            requestFileDownload.Method = WebRequestMethods.Ftp.DownloadFile;
            FtpWebResponse responseFileDownload = (FtpWebResponse)requestFileDownload.GetResponse();
            Stream responseStream = responseFileDownload.GetResponseStream();
            FileStream writeStream = new FileStream(LocalDirectory + "/" + FileName, FileMode.Create);
            int Length = 2048;
            Byte[] buffer = new Byte[Length];
            int bytesRead = responseStream.Read(buffer, 0, Length);
            while (bytesRead > 0)
            {
                writeStream.Write(buffer, 0, bytesRead);
                bytesRead = responseStream.Read(buffer, 0, Length);
            }
            responseStream.Close();
            writeStream.Close();
            requestFileDownload = null;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Upload File from Local Machine to the FTP Server in C#
The following C# code will upload a file from local machine to FTP server.

string _ftpURL = "testftp.com";             //Host URL or address of the FTP server
string _UserName = "admin";                 //User Name of the FTP server
string _Password = "admin123";              //Password of the FTP server
string _ftpDirectory = "Receipts";          //The directory in FTP server where the files will be uploaded
string _FileName = "test1.csv";             //File name, which one will be uploaded
string _LocalDirectory = "D:\\FilePuller";  //Local directory from where the files will be uploaded
UploadFile(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName, _LocalDirectory); 

public void UploadFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName, string LocalDirectory)
{
    //Comming soon....
}

Delete File from the FTP Server in C#
The following C# code will delete a file from the FTP server.

string _ftpURL = "testftp.com";     //Host URL or address of the FTP server
string _UserName = "admin";         //User Name of the FTP server
string _Password = "admin123";      //Password of the FTP server
string _ftpDirectory = "Receipts";  //The directory in FTP server where the files will be uploaded
string _FileName = "test1.csv";     //File name, which one will be uploaded
DeleteFile(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName);

public void DeleteFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName)
{
    FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName);
    ftpRequest.Credentials = new NetworkCredential(UserName, Password);
    ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
    FtpWebResponse responseFileDelete = (FtpWebResponse)ftpRequest.GetResponse();
}

Move File from One Directory to Another in the FTP Server in C#
The following C# code will move file from one directory to another in FTP server.

string _ftpURL = "testftp.com";         //Host URL or address of the FTP server
string _UserName = "admin";             //User Name of the FTP server
string _Password = "admin123";          //Password of the FTP server
string _ftpDirectory = "Receipts";      //The directory in FTP server where the file will be uploaded
string _FileName = "test1.csv";         //File name, which one will be uploaded
string _ftpDirectoryProcessed = "Done"; //The directory in FTP server where the file will be moved
MoveFile(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName, _ftpDirectoryProcessed);


public void MoveFile(string ftpURL, string UserName, string Password, string ftpDirectory, string ftpDirectoryProcessed, string FileName)
{
    FtpWebRequest ftpRequest = null;
    FtpWebResponse ftpResponse = null;
    try
    {
        ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName);
        ftpRequest.Credentials = new NetworkCredential(UserName, Password);
        ftpRequest.UseBinary = true;
        ftpRequest.UsePassive = true;
        ftpRequest.KeepAlive = true;
        ftpRequest.Method = WebRequestMethods.Ftp.Rename;
        ftpRequest.RenameTo = ftpDirectoryProcessed + "/" + FileName;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

Check File Existence in the FTP Server in C#
The following C# code will check if a file is present or not in the FTP server.

string _ftpURL = "testftp.com";     //Host URL or address of the FTP server
string _UserName = "admin";         //User Name of the FTP server
string _Password = "admin123";      //Password of the FTP server
string _ftpDirectory = "Receipts";  //The directory in FTP server where the file will be checked
string _FileName = "test1.csv";     //File name, which one will be checked
CheckFileExistOrNot(_ftpURL, _UserName, _Password, _ftpDirectory, _FileName);

public bool CheckFileExistOrNot(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName)
{
    FtpWebRequest ftpRequest = null;
    FtpWebResponse ftpResponse = null;
    bool IsExists = true;
    try
    {
        ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL + "/" + ftpDirectory + "/" + FileName);
        ftpRequest.Credentials = new NetworkCredential(UserName, Password);
        ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize;
        ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
        ftpResponse.Close();
        ftpRequest = null;
    }
    catch (Exception ex)
    {
        IsExists = false;
    }
    return IsExists;
}

In this way we can transfer files from ftp server in C#. Hope you all enjoy this article. We can also Download, Upload files from SFTP Server in C# .

Rashedul Alam

I am a software engineer/architect, technology enthusiast, technology coach, blogger, travel photographer. I like to share my knowledge and technical stuff with others.

View all posts by Rashedul Alam →

18 thoughts on “Download, Upload,Delete Files from FTP Server Using C#

    1. Hi i am using above code, but i am facing 451 error. please let me know solution.

      Thanks in Advance.
      Durga.

  1. public void UploadFile(string ftpURL, string UserName, string Password, string ftpDirectory, string FileName, string LocalDirectory)
    {
    //Comming soon…. WHEN??
    }

  2. Hello, this post helped me a great time. Thanks a ton !
    Would you kindly please add the code of uploading a file ?

    1. You have to do somethings with files when they are created. You can set or add date time with the files during its creations. Then select the 3 months old files and delete.

  3. upload image to FTP
    byte[] data;
    using (Image image = Image.FromFile(@”image path”))
    {
    using (MemoryStream m = new MemoryStream())
    {
    image.Save(m, image.RawFormat);
    data = m.ToArray();
    }
    }

    FTPHelper ftpHelper = new FTPHelper(“ftp path”, “user name”, “password”);
    ftpHelper.Upload(new MemoryStream(data), “test.jpeg”);
    ————————————————————————————–
    public class FTPHelper
    {
    public FTPHelper(string address, string login, string password)
    {
    Address = address;
    Login = login;
    Password = password;
    }

    public void Upload(MemoryStream stream, string fileName)
    {
    try
    {
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Address + @”/” + fileName);
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(Login, Password);

    request.UseBinary = true;

    byte[] buffer = new byte[stream.Length];
    stream.Read(buffer, 0, buffer.Length);
    stream.Close();

    Stream requestStream = request.GetRequestStream();
    requestStream.Write(buffer, 0, buffer.Length);
    requestStream.Close();

    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
    Console.WriteLine(“Upload File Complete, status {0}”, response.StatusDescription);
    response.Close();
    }
    catch (Exception)
    {
    throw;
    }
    }

    public string Address { get; set; }
    public string Login { get; set; }
    public string Password { get; set; }
    }

  4. Move File from One Directory to Another in the FTP Server in C#

    Got below error->

    Message = “The remote server returned an error: (451) Local error in processing.”

  5. Pingback: 1reality

Leave a Reply

Your email address will not be published. Required fields are marked *