Reputation: 1188
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!
Upvotes: 3
Views: 2609
Reputation: 202504
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();
Upvotes: 2
Reputation: 9155
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();
Upvotes: 5
Reputation: 2576
Despite its naming, Files
collection contains not only files, but all directory entries, including current and parent directory references.
If you want to count only files, filter them by IsDirectory
property:
var filesCount = session.ListDirectory(dir).Files.Where(x => !x.IsDirectory).Count();
There's also IsParentDirectory
and IsThisDirectory
properties in the latest versions to filter ".." and "." cases without name comparison.
Upvotes: 0
Reputation: 728
Instead of using ListDirectory
you can use EnumerateRemoteFiles
and it wont include ".." and "."
"." and ".." mean this directory and parent directory respectively.
Upvotes: 3