Working With FTP Using C#

File Transfer Protocol (FTP) is a network protocol for file transfer. Learn building a C# FTP app in ASP.NET using the FTP protocol.

Introduction

 
In this article, we will learn about FTP and using operations with ASP.NET. We have an FTP Client to interact and do operations on FTP systems so that we can easily add a file and easily download a file from FTP through source code to avoid manual operations. Before starting, we must know about FTP and its usage.
 

What is FTP?

 
FTP is built on a client-server model architecture and uses separate control and data connections between the client and the server. FTP users may authenticate themselves with a clear-text sign-in protocol, normally in the form of a username and password, but can connect anonymously if the server is configured to allow it.
 
For secure transmission that protects the username and password, and encrypts the content, FTP is often secured with SSL/TLS (FTPS). SSH File Transfer Protocol (SFTP) is sometimes also used instead but is technologically different.
 

First, we create the folder on FTP using C#

 
For this, we need an FTP Host, Username, and Password.
  1. string host = "ftp://192.168.1.103:24";
  2. string UserId = "VISION-PC";
  3. string Password = "vision";

  4. public bool CreateFolder()  
  5. {  
  6.            string path = "/Index";  
  7.            bool IsCreated = true;  
  8.            try  
  9.            {  
  10.                    WebRequest request = WebRequest.Create(host + path);  
  11.                    request.Method = WebRequestMethods.Ftp.MakeDirectory;  
  12.                    request.Credentials = new NetworkCredential(UserId, Password);  
  13.                    using (var resp = (FtpWebResponse)request.GetResponse())  
  14.                    {  
  15.                        Console.WriteLine(resp.StatusCode);  
  16.                    }  
  17.            }  
  18.            catch (Exception ex)  
  19.            {  
  20.                IsCreated = false;  
  21.            }  
  22.            return IsCreated;  
  23. }  
Using this function, you can create a folder on FTP. In this code, I used four variables -
  1. host (assign yout FTP host)
  2. UserId (assign your UserId to it) 
  3. Password (assign your FTP Password)
  4. Path (assgin the Path with Foldername which ypu want to create)
Below code is used to check if the folder exists or not.
  1. public bool DoesFtpDirectoryExist(string dirPath)  
  2. {  
  3.            bool isexist = false;  
  4.   
  5.            try  
  6.            {  
  7.                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);  
  8.                request.Credentials = new NetworkCredential(UserId, Password);  
  9.                request.Method = WebRequestMethods.Ftp.ListDirectory;  
  10.                using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())  
  11.                {  
  12.                    isexist = true;  
  13.                }  
  14.            }  
  15.            catch (WebException ex)  
  16.            {  
  17.                if (ex.Response != null)  
  18.                {  
  19.                    FtpWebResponse response = (FtpWebResponse)ex.Response;  
  20.                    if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)  
  21.                    {  
  22.                        return false;  
  23.                    }  
  24.                }  
  25.            }  
  26.            return isexist;  
  27. }  
In the above function, we used the dirPath parameter for checking if the directory exists or not.
 
Now, let us call the function.
  1. DoesFtpDirectoryExist("ftp://192.168.1.103:24/Kaushik")  
This function checks if the "Kaushik" folder exists or not on the root path. If it exists, then it returns True, otherwise, it returns False.
 
For Uploading File,
  1. public void UploadFile()  
  2.  {  
  3.             string From = @"F:\Kaushik\Test.xlsx";  
  4.             string To = "ftp://192.168.1.103:24/directory/Test.xlsx";  
  5.   
  6.             using (WebClient client = new WebClient())  
  7.             {  
  8.                 client.Credentials = new NetworkCredential(UserId, Password);  
  9.                 client.UploadFile(To, WebRequestMethods.Ftp.UploadFile,From);  
  10.             }  
  11.  }  
In "From" parameter assign a path from where and which file you want to upload.
 
In "To" parameter assign a path for where you want to upload a file with which name.
 
Using this function you can upload your system file to FTP server.
 
For getting a list of folders and files from a specific folder. 
  1. private List<string> GetAllFtpFiles(string ParentFolderpath)  
  2. {    
  3.             try  
  4.             {  
  5.                 FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ParentFolderpath);  
  6.                 ftpRequest.Credentials = new NetworkCredential(UserId, Password);  
  7.                 ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;  
  8.                 FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();  
  9.                 StreamReader streamReader = new StreamReader(response.GetResponseStream());  
  10.   
  11.                 List<string> directories = new List<string>();  
  12.   
  13.                 string line = streamReader.ReadLine();  
  14.                 while (!string.IsNullOrEmpty(line))  
  15.                 {  
  16.                     var lineArr = line.Split('/');  
  17.                     line = lineArr[lineArr.Count() - 1];  
  18.                     directories.Add(line);  
  19.                     line = streamReader.ReadLine();  
  20.                 }  
  21.   
  22.                 streamReader.Close();  
  23.   
  24.                 return directories;  
  25.             }  
  26.             catch (Exception ex)  
  27.             {  
  28.                 throw ex;  
  29.             }  
  30. }  
Below, we call the above function
  1. GetAllFtpFiles("ftp://192.168.1.103:24/Active")  
This function returns a list of files and folders which is in "Active" folder.
 
For deleting the file or folder,
  1. public static void DeleteFTPFolder(string Folderpath)  
  2. {
  3.             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Folderpath);  
  4.             request.Method = WebRequestMethods.Ftp.RemoveDirectory;  
  5.             request.Credentials = new System.Net.NetworkCredential(UserId, Password); ;  
  6.             request.GetResponse().Close();  
  7. }  
In the below line, we called the above function.
  1. DeleteFTPFolder("ftp://192.168.1.103:24/directory");