【问题标题】:Upload all files matching wildcard to SFTP将所有匹配通配符的文件上传到 SFTP
【发布时间】:2017-06-17 18:12:38
【问题描述】:

我正在使用 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();

【问题讨论】:

  • E:\Zatpark\*.xml 对我来说似乎不是一个有效的路径。您的 Sftp 实现是否明确允许这样的传输? (如果确实如此,我会感到惊讶)。这可能是 "illegal characters in path" 错误的原因,因为* 不是有效的路径字符。顺便说一句:你应该真正决定一个单一的命名约定,即使在这个简短的代码中你使用了三个不同的。
  • 如果您想在路径中使用通配符掩码并使用其他第三方库可能是一种选择,您可能需要查看此componentpro.com/sftp.net,示例如下:componentpro.com/doc/sftp/upload-files.htm

标签: c# .net sftp sharpssh


【解决方案1】:

不要使用 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 方法。它的实现很奇怪,如果没有破坏的话。它基本上只支持完全由*? 组成的掩码。

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 2014-02-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 2015-07-24
    • 1970-01-01
    • 2019-03-19
    相关资源
    最近更新 更多