How to get the files of remote directory using a pattern with C# and WinSCP

不羁岁月 提交于 2019-12-22 12:36:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!