Reputation: 13
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUrl);
request.Method = WebRequestMethods.Ftp.ListDirectory;
var response = (FtpWebResponse)request.GetResponse();
Stream rStream = response.GetResponseStream();
StreamReader reader = new StreamReader(rStream);
string fileNames = reader.ReadToEnd();
List<string> ls = fileNames.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
for (int i = 0; i < ls.Count; i++)
Console.WriteLine(ls[i]);
This method only lists files present in the specified serverUrl directory . I want to list all the files of the FTP server. Can anyone suggest me anything?
Upvotes: 0
Views: 1483
Reputation: 5986
I have written the related code in the msdn forum like: download each file in folder.
You can use the FtplistFile method to get a list of all files in the ftp server.
Here is a code example I modified.
private void button1_Click(object sender, EventArgs e)
{
string uri = "ftp://xxx.x.xx.x/";
string username = "USERNAME";
string password = "PASSWORD";
ListFtpDirectory(uri, new NetworkCredential(username, password));
}
static void ListFtpDirectory(string url, NetworkCredential credentials)
{
WebRequest listRequest = WebRequest.Create(url);
listRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
listRequest.Credentials = credentials;
List<string> lines = new List<string>();
using (WebResponse listResponse = listRequest.GetResponse())
using (Stream listStream = listResponse.GetResponseStream())
using (StreamReader listReader = new StreamReader(listStream))
{
while (!listReader.EndOfStream)
{
string line = listReader.ReadLine();
lines.Add(line);
}
}
foreach (string line in lines)
{
string[] tokens =
line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string name = tokens[3];
string permissions = tokens[2];
if (permissions == "<DIR>")
{
Console.WriteLine($"Directory {name}");
string fileUrl = url + name;
ListFtpDirectory(fileUrl + "/", credentials);
}
else
{
Console.WriteLine(url+name);
Console.WriteLine($"File {name}");
}
}
}
Get file name:
Get file path in ftp:
Upvotes: 0