问题
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?
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftp_root + path);
request.Method = WebRequestMethods.Ftp.ListDirectory;
FileZilla lists the hidden files correctly so I know the FTP server is returning that data to it. I just need to replicate that with FtpWebRequest
. Or use a different library for it.
回答1:
The FtpWebRequest
which is provided by Microsoft does not perform all the operations neccessary for listing FTP, FTPS or SFTP site's directories.
A good solution would be to use some other dll's like WinScp, Ftp.dll which can provide you with some efficient and extra functionalities.
回答2:
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");
来源:https://stackoverflow.com/questions/42429441/ftpwebrequest-listdirectory-does-not-return-hidden-files