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

时间:2017-02-01 05:10:36

标签: c# .net sftp sharpssh

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

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

  

路径中的非法字符。

如果我尝试使用确切的文件名上传,则会传输文件而不会出现任何问题。

每次我尝试上传两个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();

1 个答案:

答案 0 :(得分:4)

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

如果切换到不支持通配符的SSH.NET库,则必须使用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方法。它的实现很奇怪,如果不破坏的话。它基本上只支持完全由*?组成的掩码。