Introduction
In this article, we will learn about FTP and its 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.
string host = "ftp://192.168.1.103:24";
string UserId = "VISION-PC";
string Password = "vision";
public bool CreateFolder()
{
string path = "/Index";
bool IsCreated = true;
try
{
WebRequest request = WebRequest.Create(host + path);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
request.Credentials = new NetworkCredential(UserId, Password);
using (var resp = (FtpWebResponse)request.GetResponse())
{
Console.WriteLine(resp.StatusCode);
}
}
catch (Exception ex)
{
IsCreated = false;
}
return IsCreated;
}
Using this function, you can create a folder on FTP. In this code, I used four variables.
- host (assign you FTP host)
- UserId (assign your UserId to it)
- Password (assign your FTP Password)
- Path (assign the Path with the Foldername which you want to create)
The below code is used to check if the folder exists or not.
public bool DoesFtpDirectoryExist(string dirPath)
{
bool isExist = false;
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(dirPath);
request.Credentials = new NetworkCredential(UserId, Password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
isExist = true;
}
}
catch (WebException ex)
{
if (ex.Response != null)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
}
return isExist;
}
In the above function, we used the dirPath parameter to check if the directory exists or not.
Now, let us call the function.
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,
public void UploadFile()
{
string from = @"F:\Kaushik\Test.xlsx";
string to = "ftp://192.168.1.103:24/directory/Test.xlsx";
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(UserId, Password);
client.UploadFile(to, WebRequestMethods.Ftp.UploadFile, from);
}
}
In the "From" parameter, assign a path from where and which file you want to upload.
In the "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 the FTP server.
To get a list of folders and files from a specific folder.
private List<string> GetAllFtpFiles(string parentFolderPath)
{
try
{
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(parentFolderPath);
ftpRequest.Credentials = new NetworkCredential(UserId, Password);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
var lineArr = line.Split('/');
line = lineArr[lineArr.Count() - 1];
directories.Add(line);
line = streamReader.ReadLine();
}
streamReader.Close();
return directories;
}
catch (Exception ex)
{
throw ex;
}
}
Below, we call the above function.
GetAllFtpFiles("ftp://192.168.1.103:24/Active");
This function returns a list of files and folders which is in the "Active" folder.
For deleting the file or folder,
public static void DeleteFTPFolder(string folderPath)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderPath);
request.Method = WebRequestMethods.Ftp.RemoveDirectory;
request.Credentials = new System.Net.NetworkCredential(UserId, Password);
request.GetResponse().Close();
}
In the line below, we call the above function.
DeleteFTPFolder("ftp://192.168.1.103:24/directory");