我用c#编写了一个程序,它使用WinSCP . net递归地在SFTP站点中搜索特定的子文件夹模式,然后递归地枚举这些目录的内容。
程序可以工作,但是每个方法的前半部分是相同的。有很多关于会话设置和会话启动的样板文件。是否有一种方法,我可以只是定义一次公开,然后从每个方法引用会话?
感谢您的帮助。
using WinSCP;
class Sanity
{
public static int Main()
{
try
{
// Setup session options
SessionOptions settings = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "",
UserName = "",
Password = "",
SshHostKeyFingerprint = ""
};
using (Session session = new Session())
{
session.Open(settings); // Connect
string homeDir = "/something";
RemoteDirectoryInfo directory =
session.ListDirectory(homeDir); // Set root location
foreach (RemoteFileInfo file in directory.Files) // Loop over the directories
{
LookDir(file.FullName); // Pass each parent directory
}
}
return 0;
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
return 1;
}
}
public static void LookDir(string dir) // Searches for the Inbound folder
{
// Setup session options
SessionOptions settings = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "",
UserName = "",
Password = "",
SshHostKeyFingerprint = ""
};
using (Session session = new Session())
{
// Connect
session.Open(settings);
RemoteDirectoryInfo directory =
session.ListDirectory(dir);
foreach (RemoteFileInfo file in directory.Files)
{
if (!file.FullName.Contains(".") && file.IsDirectory) {
LookDir(file.FullName); //Recursive
if (file.FullName.EndsWith("/Inbound")) {
Console.WriteLine("Passing " + file.FullName + " for analysis");
FileCheck(file.FullName); // Pass Inbound for enumeration
}
}
}
}
}
public static void FileCheck(string Nug) //Recursively checks the Inbound folder for files
{
SessionOptions settings = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "",
UserName = "",
Password = "",
SshHostKeyFingerprint = ""
};
using (Session session = new Session())
{
// Connect
session.Open(settings);
IEnumerable<RemoteFileInfo> fileInfos =
session.EnumerateRemoteFiles(Nug, "*", WinSCP.EnumerationOptions.AllDirectories);
int count = fileInfos.Count();
if (count > 0) {
Console.WriteLine("It contains " + count + " files");
}
}
}
}
我确实试图将会话传递给类变量或参数,但我得到错误。我不确定我想要的是否可能。
如果您只想打开会话一次,使用如下方法:
Session _session = null;
private Session GetSession()
{
if (_session == null)
{
var settings = new SessionOptions
{
Protocol = Protocol.Sftp,
HostName = "",
UserName = "",
Password = "",
SshHostKeyFingerprint = ""
};
var session = new Session();
session.Open();
_session = session;
}
return _session;
}
但是您还需要确保在程序结束时处置_session
。你需要确保你从来没有尝试并行使用_session
多次。
如果你只是想排除Session
的创建,请参见:
使用ASP Session变量创建WinSCP SessionOptions,使其可以在多个方法之间重用