In this blog post, we will explore how we can access FTP server and how we can download a file or complete folder based on access rights.
Once files or folders are downloaded, we also delete files from FTP server to keep our FTP repository tidy.
Access FTP Server (Create a connection)
To access FTP server we need following;
- A valid User name (user name that has access to explore FTP repository)
- A valid password
- FTP URL with the port. (Normally FTP uses port 25 but some service provider may change this port number)
Now we need to create an FTPRequest (System.Net) to talk with FTP server. This is a simple Web request, it contains NetworkCredential (System.Net) & FTP server Url.
So first step, create NetworkCredential
var credentials = new NetworkCredential("FTP-Username", "FTP-Password");
After that we will create complete request object like below
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create("FTP-Url");
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
and get response from FTP server based on our Request
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
You might have noticed that in our request object, our request method is “ListDirectoryDetails”. This is because we want to get list of files and directories from our FTP repository and later we will decide if we want to delete or keep these files. Your request method or scenario might be different. There are following request methods you can use
- ListDirectoryDetails
- AppendFile
- DeleteFile
- DownloadFile
- GetDateTimestamp
- GetFileSize
- ListDirectory
- MakeDirectory
- PrintWorkingDirectory
- RemoveDirectory
- Rename
- UploadFile
- UploadFileWithUniqueName
now we have response from FTP server we can read response and see list of files.
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
// ==== Do sometime ====
}
Get Files / Directories from FTP
We can create a simple method that will download all files and directories from FTP using above code examples. Let’s call it “DownloadFtpFilesDirectory”. This method takes
- User Name
- Password
- Url
- Local directory path
to create FTP request and download files and complete directories in local drive.
static void DownloadFtpFilesDirectory(string url, NetworkCredential credentials, string localPath)
{
FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
lines.Add(listReader.ReadLine());
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 4, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[3];
string permissions = tokens[2];
string fileUrl = url + name;
if (permissions[1] == 'D')
{
// line contains Directory
string localFilePath = Path.Combine(localPath, name);
//recursive function
DownloadFtpFilesDirectory(fileUrl + "/", credentials, localFilePath);
}
else
{
// line contains file
FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;
downloadRequest.Credentials = credentials;
using (FtpWebResponse downloadResponse =
(FtpWebResponse)downloadRequest.GetResponse())
using (Stream sourceStream = downloadResponse.GetResponseStream())
using (Stream targetStream = File.Create(Path.Combine(localPath, name)))
{
byte[] buffer = new byte[10240];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0)
{
targetStream.Write(buffer, 0, read);
}
}
}
}
}
Delete Files or Directories from FTP
Delete Files
FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
deleteRequest.Credentials = credentials;
FtpWebResponse response = (FtpWebResponse)deleteRequest.GetResponse();
response.Close();
Delete Directory
FtpWebRequest deleteRequest = (FtpWebRequest)WebRequest.Create(fileUrl);
deleteRequest.Method = WebRequestMethods.Ftp.RemoveDirectory;
deleteRequest.Credentials = credentials;
FtpWebResponse response = (FtpWebResponse)deleteRequest.GetResponse();
response.Close();