调用FtpClient一次以递归方式列出目录

时间:2015-03-05 04:45:52

标签: c# ftp ftp-client

我有一个递归函数:

class FtpFolder{
public void ListChildren(IFolder folder)
{
    Uri uri = new Uri("ftp://127.0.0.1/");
    FtpClient ftpClient = new FtpClient();
    ftpClient.Host = uri.Host;
    ftpClient.Credentials = new NetworkCredential("UserLocal", "1234");
    ftpClient.SetWorkingDirectory(folder.FullName);
    foreach (FtpListItem item in ftpClient.GetListing(ftpClient.GetWorkingDirectory(), FtpListOption.Modify | FtpListOption.Size))
    {
        switch (item.Type)
        {
            case FtpFileSystemObjectType.Directory:
                FtpFolder ftpSubFolder = new FtpFolder(item);
                folder.Folders.Add(ftpSubFolder);
                ListChildren(ftpSubFolder);
                break;
            case FtpFileSystemObjectType.File:
                folder.Files.Add(new FtpFile() { Item = item });
                break;
        }
    }
}
}

这是我的班级连接

class Connection{
private uri Uri;
private string Username;
private string Password
public connection(uri _uri, string _username, _password){
_uri=Uri; _username=Username; _password=Password;
}
public void connect(){
}
}

我使用此递归函数列出来自FTP服务器的所有文件。我的问题是我可以重用FtpClient的单个实例,所以我不需要继续重新创建一个新实例吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

public void ListChildren(IFolder folder)
{
    FtpClient ftpClient = new FtpClient
    {
        Host = new Uri("ftp://127.0.0.1/").Host,
        Credentials = new NetworkCredential("UserLocal", "1234");
    };
    ftpClient.SetWorkingDirectory(folder.FullName);

    ListChildren(ftpClient, ftpClient.GetWorkingDirectory());
}

private void ListChildren(FtpClient ftpClient, IFolder folder)
{
    foreach (FtpListItem item in folder, FtpListOption.Modify | FtpListOption.Size))
    {
        switch (item.Type)
        {
            case FtpFileSystemObjectType.Directory:
                FtpFolder ftpSubFolder = new FtpFolder(item);
                folder.Folders.Add(ftpSubFolder);

                ListChildren(ftpSubFolder);
                break;
            case FtpFileSystemObjectType.File:
                folder.Files.Add(new FtpFile { Item = item });
                break;
        }
    }
}