I'm trying to download the contents of an FTP folder to a local folder using a this example on StackOverflow:
Downloading a list of files from ftp to local folder using c#?
The code I have at the moment is:
public void DownloadFilesFromFTP(string localFilesPath, string remoteFTPPath)
{
remoteFTPPath = "ftp://" + Hostname + remoteFTPPath;
var request = (FtpWebRequest)WebRequest.Create(remoteFTPPath);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(Username, Password);
request.Proxy = null;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
List<string> directories = new List<string>();
string line = reader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
directories.Add(line);
line = reader.ReadLine();
}
reader.Close();
using (WebClient ftpClient = new WebClient())
{
ftpClient.Credentials = new System.Net.NetworkCredential(Username, Password);
for (int i = 0; i <= directories.Count - 1; i++)
{
if (directories[i].Contains("."))
{
string path = remoteFTPPath + @"/" + directories[i].ToString();
string trnsfrpth = localFilesPath + @"\" + directories[i].ToString();
ftpClient.DownloadFile(path, trnsfrpth);
}
}
}
response.Close();
}
I'm receiving a path not supported exception and when I inspect the values of my variables path
and trnsfrpth
they appear to be including Apache information.
path: ftp://hostname/data/resourceOrders/-rw-r--r-- 1 apache
apache 367 Jul 16 14:07 resource-orders-1437019656813-893.json
And
trnsfrpth: V:\code.runner\local\orders-rw-r--r-- 1 apache apache
367 Jul 16 14:07 resource-orders-1437019656813-893.json
How can I capture just the filename, resource-orders-1437019656813-893.json
without a hacky (rightof()
, for example) approach?
To retrieve just list of file names without additional details, use WebRequestMethods.Ftp.ListDirectory
(FTP command NLST
), instead of WebRequestMethods.Ftp.ListDirectoryDetails
(FTP command LIST
).