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");
Gladson ReisPosted Apr 22, 2024, 4:04 AM
Thanks, Perfect !
Rey ChabbyPosted Apr 4, 2022, 5:09 PM
DirectoryNotFoundException: Could not find a part of the path "C:\public_html\files\profileimg\dog.jpg".System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean anonymous, System.IO.FileOptions options) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.Int32 bufferSize, System.Boolean isAsync, System.Boolean anonymous) (at <695d1cc93cca45069c528c15c9fdd749>:0) System.IO.FileStream..ctor (System.String path, System.IO.FileMode mode, System.IO.FileAccess access) (at <695d1cc93cca45069c528c15c9fdd749>:0) (wrapper remoting-invoke-with-check) System.IO.FileStream..ctor(string,System.IO.FileMode,System.IO.FileAccess) System.Net.WebClient.OpenFileInternal (System.Boolean needsHeaderAndBoundary, System.String fileName, System.IO.FileStream& fs, System.Byte[]& buffer, System.Byte[]& formHeaderBytes, System.Byte[]& boundaryBytes) (at <0463b2ef957545c0a51b42f372cd4fbb>:0) System.Net.WebClient.UploadFile (System.Uri address, System.String method, System.String fileName) (at <0463b2ef957545c0a51b42f372cd4fbb>:0) Rethrow as WebException: An exception occurred during a WebClient request. System.Net.WebClient.UploadFile (System.Uri address, System.String method, System.String fileName) (at <0463b2ef957545c0a51b42f372cd4fbb>:0) System.Net.WebClient.UploadFile (System.String address, System.String method, System.String fileName) (at <0463b2ef957545c0a51b42f372cd4fbb>:0) (wrapper remoting-invoke-with-check) System.Net.WebClient.UploadFile(string,string,string) web+<ShowLoadDialogCoroutine>d__25.MoveNext () (at Assets/scripts/web.cs:178) UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) (at <07c89f7520694139991332d3cf930d48>:0)
Rey ChabbyPosted Apr 4, 2022, 5:09 PM
Hi Kaushik I would like to ask regarding the file upload, my project shows an error of
hamza hameedPosted Apr 16, 2021, 11:35 PM
Very helpfull ,thanks
Sriram RPosted Oct 10, 2020, 6:19 AM
Hi Kaushik, Its good Article more use full, i need help. am looking for another concern using c# programming to change FTP Password. .Please help
Sriram RPosted Oct 10, 2020, 6:17 AM
Hi Kaushik,
Arun SharmaPosted Jul 20, 2020, 1:14 PM
Hi, It is a helpful article. I used your file upload feature in my project and seamlessly I implemented this. Now I want download the file from FTP and once file has been downloaded , file must move or archived on different folder on same FTP. Please help
Blessy SomiPosted Mar 21, 2020, 8:15 AM
Hi, It is a helpful article. Thank you so much. Actually, I am looking for another concern regarding crystal report. I uploaded one rpt file in ftp. From my VB.net application I want to load that file. Is it possible to do so? If possible, can you please help me.
Pankajkumar PatelPosted Jul 31, 2019, 1:20 AM
Helpful article
Amit MohantyPosted Jul 31, 2019, 12:06 AM
Nice article