How to remove "." and ".." files from remote directory with C# and WinSCP
I'm trying to get the files count from a remote directory using a SFTP connection, but I'm getting .
and ..
and these are counted these dots like a files, I have 2 files in the remote directory but is counting 4 files including .
and ..
.
Someone can help me how to solve this?
This is my code:
filesCount = session.ListDirectory(DataFile.sRemoteDirectory).Files.Count;
Thanks!
According to the WinSCP documentation:
You can use
Session.EnumerateRemoteFiles
method instead, if you want to:
- List only files matching a wildcard;
- List the files recursively;
- Have references to this (.) and parent (..) directories be excluded form the listing.
So it appears that you should change your code to do something more like this:
filesCount = 0;
filesCount = session.EnumerateRemoteFiles(DataFile.sRemoteDirectory).Files.Count();
session.Close();
Instead of using ListDirectory
you can use EnumerateRemoteFiles
and it wont include ".." and "."
"." and ".." mean this directory and parent directory respectively.
The .
and ..
are references to this and parent directories respectively on most file systems.
To filter them, you can use new properties .IsThisDirectory
and .IsParentDirectory
of the RemoteFileInfo
class:
filesCount =
session.ListDirectory(DataFile.sRemoteDirectory).Files
.Where(file => !file.IsThisDirectory && !file.IsParentDirectory).Count();
Note that you have to use the Enumerable.Count()
extension method, instead of the ICollection.Count
property as the result of the Enumerable.Where()
is the IEnumerable
, not the Collection
anymore.
Or to make it even easier, use the Session.EnumerateRemoteFiles()
method, which with the EnumerationOptions.None
option is functionally equivalent to the Session.ListDirectory()
, just that it excludes the .
and ..
.
filesCount =
session.EnumerateRemoteFiles(
DataFile.sRemoteDirectory, null, EnumerationOptions.None).Count();
If you want to filter all directories, use:
filesCount =
session.ListDirectory(DataFile.sRemoteDirectory).Files
.Where(file => !file.IsDirectory).Count();