如何使用WinSCP .NET程序集读取文本文件?

时间:2015-09-25 10:11:59

标签: c# text-files sftp winscp winscp-net

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

1 个答案:

答案 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