将所有匹配通配符的文件上传到 SFTP

Upload all files matching wildcard to SFTP

我正在使用 Tamir SharpSSH 将文件从远程传输到本地,反之亦然,没有任何问题。

但是,当我尝试通过 SFTP 上传多个 XML 文件时收到错误消息:

Illegal characters in path.

如果我尝试使用准确的文件名上传,它会毫无问题地传输文件。

每次我尝试上传两个 XML 个文件:

KDO_E2D_A21_AA769_20170124_143123.xml
KDO_E2D_A21_AA776_20170130_143010.xml
string ftpURL = "11.11.11.1";
string userName = "Aaaaaa"; //User Name of the SFTP server
string password = "hah4444"; //Password of the SFTP server
int port = 22; //Port No of the SFTP server (if any)

//The directory in SFTP server where the files will be uploaded
string ftpDirectory = "/home/A21sftp/kadoe/";

//Local directory from where the files will be uploaded 
string localDirectory = "E:\Zatpark\*.xml"; 

Sftp Connection = new Sftp(ftpURL, userName, password);
Connection.Connect(port);
Connection.Put(localDirectory, ftpDirectory); 
Connection.Close();

不要使用 Tamir.SharpSSH,这是一个死项目。使用一些 up to date SSH/SFTP implementation.


如果您像 SSH.NET that does not support wildcards, you have to use the Directory.GetFiles method 那样切换到库来查找要上传的文件:

SftpClient client = new SftpClient("example.com", "username", "password");
client.Connect();

string localDirectory = @"E:\Zatpark upload";
string localPattern = "*.xml";
string ftpDirectory = "/dv/inbound/";
string[] files = Directory.GetFiles(localDirectory, localPattern);
foreach (string file in files)
{
    using (Stream inputStream = new FileStream(file, FileMode.Open))
    {
        client.UploadFile(inputStream, ftpDirectory + Path.GetFileName(file));
    }
}

或者使用支持通配符的库。

例如 WinSCP .NET assembly(虽然不是纯 .NET 程序集),您可以:

SessionOptions sessionOptions = new SessionOptions
{
    Protocol = Protocol.Sftp,
    HostName = "example.com",
    UserName = "username",
    Password = "password",
    SshHostKeyFingerprint = "ssh-dss ...",
};

using (Session session = new Session())
{
    session.Open(sessionOptions);
    string ftpDirectory = "/dv/inbound/"; 
    string localDirectory = @"E:\Zatpark upload\*.xml";
    session.PutFiles(localDirectory, ftpDirectory).Check();
}

你可以code template generated in WinSCP GUI.

(我是WinSCP的作者)


要解释为什么您的代码不起作用:检查 ChannelSftp.glob_local 方法。它的实现很奇怪,即使没有被破坏。它基本上只支持完全由 *? 组成的掩码。