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) 例Listing files matching wildcardも参照してください。

于 2015-09-25T11:26:43.197 に答える