问题
I'm trying to get an specific files from a remote server with FTP/SFTP connection, the issue that I'm having is, I'm trying to get the count of files in the remote directory with an specific pattern. I'm using a mask but is not working for me, it throwing an exception: this is what I have
DataFile.sRemoteDirectory = "/user/ftpuser/test/";
receivepattern = "Del*";
filesCount =
session.ListDirectory(
session.EscapeFileMask(DataFile.sRemoteDirectory + receivepattern))
.Files.Where(x => !x.IsDirectory).Count();
回答1:
This is what I did and it work! hope to someone help this piece of code, I used regular expression, where receivepattern is the pattern used:
receivepattern = "^[\\d\\w]*" + receivepattern;
r = new Regex(receivepattern);
filesCount = session.ListDirectory(DataFile.sRemoteDirectory).Files.Where(x => !x.IsDirectory).Where(x => r.IsMatch(x.Name)).Count();
回答2:
The Session.ListDirectory method does not accept a wildcard, only a path.
Since, the WinSCP .NET assembly 5.9, you can use the Session.EnumerateRemoteFiles method instead:
filesCount =
session.EnumerateRemoteFiles(
DataFile.sRemoteDirectory, receivepattern, EnumerationOptions.None).Count();
In older versions, you have to filter the files returned by the Session.ListDirectory
yourself:
Regex r = new Regex("^Del.*");
filesCount = session.ListDirectory(DataFile.sRemoteDirectory).Files
.Where(x => !x.IsDirectory)
.Where(x => r.Match(x.Name))
.Count()
See the official example Listing files matching wildcard (in PowerShell though).
来源:https://stackoverflow.com/questions/34680848/how-to-get-the-files-of-remote-directory-using-a-pattern-with-c-sharp-and-winscp