我需要使用WinSCP .NET程序集查找文件名中包含特定单词的文本文件,然后从这些文件中提取一些行。 我知道它可能是一个基本问题,但我以前从未使用过SFTP连接和这个库,也不知道如何启动项目。我会感谢任何帮助。
答案 0 :(得分:0)
Session.ListDirectory
检索远程目录中的文件列表.txt
?)Session.GetFiles
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "example.com",
UserName = "user",
Password = "mypassword",
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxxxxxxxxxxxxxx..."
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
const string remotePath = "/path";
// Retrieve a list of files in a remote directory
RemoteDirectoryInfo directory = session.ListDirectory(remotePath);
// Iterate the list
foreach (RemoteFileInfo fileInfo in directory.Files)
{
// Is it a file with .txt extension?
if (!fileInfo.IsDirectory &&
fileInfo.Name.EndsWith(".txt", StringComparison.OrdinalIgnoreCase))
{
string tempPath = Path.GetTempFileName();
// Download the file to a temporary folder
var sourcePath =
RemotePath.EscapeFileMask(remotePath + "/" + fileInfo.Name);
session.GetFiles(sourcePath, tempPath).Check();
// Read the contents
string[] lines = File.ReadAllLines(tempPath);
// Retrieve what you need from lines
...
// Delete the temporary copy
File.Delete(tempPath);
}
}
}
另请参阅类似的(PowerShell)示例Listing files matching wildcard。