FtpWebRequest ListDirectory does not return hidden files

后端 未结 2 1894
南旧
南旧 2021-01-15 14:51

Using FtpWebRequest to list the contents of a directory; however, it\'s not showing the hidden files.

How do I get it to show the hidden files?

2条回答
  •  被撕碎了的回忆
    2021-01-15 15:36

    Some FTP servers fail to include hidden files to responses to LIST and NLST commands (which are behind the ListDirectoryDetails and ListDirectory).

    One solution is to use MLSD command, to which FTP servers do return hidden files. The MLSD command is anyway the only right way to talk to an FTP server, as its response format is standardized (what is not the case with LIST).

    But .NET framework/FtpWebRequest does not support the MLSD command.

    For that you would have to use a different 3rd party FTP library.

    For example with WinSCP .NET assembly you can use:

    // Setup session options
    SessionOptions sessionOptions = new SessionOptions
    {
        Protocol = Protocol.Ftp,
        HostName = "ftp.example.com",
        UserName = "user",
        Password = "mypassword",
    };
    
    using (Session session = new Session())
    {
        // Connect
        session.Open(sessionOptions);
    
        RemoteDirectoryInfo directory = session.ListDirectory("/remote/path");
    
        foreach (RemoteFileInfo fileInfo in directory.Files)
        {
            Console.WriteLine(
                "{0} with size {1}, permissions {2} and last modification at {3}",
                fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions,
                fileInfo.LastWriteTime);
        }
    }
    

    See documentation for Session.ListDirectory method.

    WinSCP will use MLSD, if the server supports it. If not, it will try to use -a trick (described below).

    (I'm the author of WinSCP)


    If you are stuck with FtpWebRequest, you can try to use -a switch with the LIST/NLST command. While that's not any standard switch (there are no switches in FTP), many FTP servers do recognize it. And it makes them return hidden files.

    To trick FtpWebRequest to add the -a switch to LIST/NLST command, add it to the URL:

    WebRequest.Create("ftp://ftp.example.com/remote/path/ -a");
    

提交回复
热议问题