我已经在 msdn 论坛中编写了相关代码,例如:下载文件夹中的每个文件。
您可以使用 FtplistFile 方法获取 ftp 服务器中所有文件的列表。
这是我修改的代码示例。
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}");
}
}
}
获取文件名:
在 ftp 中获取文件路径: