C# ftp获取文件夹下的文件夹和文件
时间: 2023-12-05 14:04:18 浏览: 228
你可以使用C#内置的FtpWebRequest和FtpWebResponse来实现FTP操作,以下是获取FTP服务器上指定目录下的所有文件和子文件夹的代码示例:
```csharp
using System;
using System.IO;
using System.Net;
public class FtpClient
{
private string ftpServer;
private string ftpUser;
private string ftpPassword;
public FtpClient(string server, string user, string password)
{
ftpServer = server;
ftpUser = user;
ftpPassword = password;
}
public void ListDirectory(string directory)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create($"ftp://{ftpServer}/{directory}");
request.Credentials = new NetworkCredential(ftpUser, ftpPassword);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
Console.WriteLine(line);
}
reader.Close();
response.Close();
}
}
```
调用方法:
```csharp
FtpClient client = new FtpClient("ftp.example.com", "username", "password");
client.ListDirectory("/path/to/directory");
```
这个示例将打印出目录中所有的文件和文件夹,包括子文件夹。如果你需要递归遍历所有子目录,可以使用递归函数来实现。
阅读全文