I have been searched in the net and I didn't found any result. Actually I want to get the name of all the files that I have in the root
and Directory
and Sub Directory
. I tried the code as bellow but its give me only the files in the root
of my FTP.
The folder that I have in the FTP is like as bellow:
/ds/product/Jan/
/ds/subproduct/Jan/
/ds/category/Jan/
The code that I tried:
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://" + FtpIP);
ftpRequest.Credentials = new NetworkCredential(FtpUser, FtpPass);
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
List<string> directories = new List<string>();
string line = streamReader.ReadLine();
while (!string.IsNullOrEmpty(line))
{
// directories.Add(line);
line = streamReader.ReadLine().ToString();
MessageBox.Show(line);
}
streamReader.Close();
It is s not easy to implement this without any external library. Unfortunately, neither the .NET Framework nor PowerShell have any explicit support for recursively listing files in an FTP directory.
You have to implement that yourself:
Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET Framework (
FtpWebRequest
). The .NET Framework unfortunately does not support theMLSD
command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.Your options are:
LIST
command =ListDirectoryDetails
method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by thed
at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)Use the function like:
If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the
MLSD
command and/or parsing variousLIST
listing formats.For example with WinSCP .NET assembly you can list whole directory recursively with a single call to
Session.EnumerateRemoteFiles
:Not only the code is simpler, more robust and platform-independent. It also makes all other file attributes (size, modification time, permissions, ownership) readily available via the
RemoteFileInfo
class.Internally, WinSCP uses the
MLSD
command, if supported by the server. If not, it uses theLIST
command and supports dozens of different listing formats.(I'm the author of WinSCP)