1

我需要使用 WinSCP .NET 程序集来查找文件名中包含特定单词的文本文件,然后从这些文件中提取一些行。我知道这可能是一个基本问题,但我以前从未使用过 SFTP 连接和这个库,也不知道如何启动该项目。我会感谢任何帮助。

4

1 回答 1

1
  • 使用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)示例列出与通配符匹配的文件

于 2015-09-25T11:26:43.197 回答