C# 如何使用WinSCP.NET程序集读取文本文件?
我需要使用WinSCP.NET汇编来查找文件名中包含特定单词的文本文件,然后从这些文件中提取一些行。 我知道这可能是一个基本问题,但我以前从未使用过SFTP连接或这个库,也不知道如何启动项目。我将感谢您的帮助。C# 如何使用WinSCP.NET程序集读取文本文件?,c#,text-files,sftp,winscp,winscp-net,C#,Text Files,Sftp,Winscp,Winscp Net,我需要使用WinSCP.NET汇编来查找文件名中包含特定单词的文本文件,然后从这些文件中提取一些行。 我知道这可能是一个基本问题,但我以前从未使用过SFTP连接或这个库,也不知道如何启动项目。我将感谢您的帮助。 使用检索远程目录中的文件列表 迭代列表以查找符合条件的文件(.txt?) 使用将匹配的文件下载到本地临时文件 阅读临时文件并查找所需的内容 另请参见类似的(PowerShell)示例。谢谢!这对我帮助很大。 // Setup session options SessionOption
- 使用检索远程目录中的文件列表
- 迭代列表以查找符合条件的文件(
?).txt
- 使用将匹配的文件下载到本地临时文件
- 阅读临时文件并查找所需的内容
另请参见类似的(PowerShell)示例。谢谢!这对我帮助很大。
// 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);
}
}
}