Sharing WinSCP .NET Session across multiple C# methods.

huangapple go评论61阅读模式
英文:

Sharing WinSCP .NET Session across multiple C# methods

问题

I've translated the code portion as requested:

我已经用C#编写了一个程序,使用WinSCP .NET,它会递归搜索SFTP站点,查找特定子文件夹模式,然后递归枚举这些目录的内容。

程序可以工作,但每个方法的前半部分都相同。会话设置和会话初始化都有很多样板代码。是否可以公开定义一次,然后从每个方法中引用会话?

任何帮助都会很感激。

我尝试将会话传递给类变量或参数,但出现错误。实际上,我不确定我想要的是否可能。


Please note that I've preserved the code structure and syntax while providing the Chinese translation.

<details>
<summary>英文:</summary>

I&#39;ve written a program in C# using WinSCP .NET which recursively searches through an SFTP site looking for a specific subfolder pattern, and then recursively enumerates the contents of those directories.

The program works, but the first half of every method is the same. There&#39;s so much boilerplate with the session settings and session initiation. Is there a way I can just define it once publicly, and then reference the session from each method? 

Any help appreciated.

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 = &quot;/something&quot;;

            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(&quot;Error: {0}&quot;, 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 = &quot;&quot;,
        UserName = &quot;&quot;,
        Password = &quot;&quot;,
        SshHostKeyFingerprint = &quot;&quot;
    };

    using (Session session = new Session())
    {
        // Connect
        session.Open(settings);

        RemoteDirectoryInfo directory = 
            session.ListDirectory(dir);

        foreach (RemoteFileInfo file in directory.Files)
        {                                      
            if (!file.FullName.Contains(&quot;.&quot;) &amp;&amp; file.IsDirectory) {
                LookDir(file.FullName);  //Recursive

                if (file.FullName.EndsWith(&quot;/Inbound&quot;)) {
                    
                    Console.WriteLine(&quot;Passing &quot; + file.FullName + &quot; for analysis&quot;);
                    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 = &quot;&quot;,
        UserName = &quot;&quot;,
        Password = &quot;&quot;,
        SshHostKeyFingerprint = &quot;&quot;
    };

    using (Session session = new Session())
    {
        // Connect
        session.Open(settings);

        IEnumerable&lt;RemoteFileInfo&gt; fileInfos =
            session.EnumerateRemoteFiles(Nug, &quot;*&quot;, WinSCP.EnumerationOptions.AllDirectories);
    
        int count = fileInfos.Count();
    
        if (count &gt; 0) {  

            Console.WriteLine(&quot;It contains &quot; + count + &quot; files&quot;);
       
        }
    }
}

}


I did attempt to pass the session to a class variable or parameter but I&#39;m getting errors. I&#39;m not actually sure if what I want is possible.


</details>


# 答案1
**得分**: 0

如果您只想打开会话一次,请使用以下方法:

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`的创建,请参考:
https://stackoverflow.com/q/74727075/850848
英文:

If you want to open the session only once, use method like this:

Session _session = null;

private Session GetSession()
{
    if (_session == null)
    {
        var settings = new SessionOptions
        {
            Protocol = Protocol.Sftp,
            HostName = &quot;&quot;,
            UserName = &quot;&quot;,
            Password = &quot;&quot;,
            SshHostKeyFingerprint = &quot;&quot;
        };
 
        var session = new Session();
        session.Open();
        _session = session;
    }
    
    return _session;
}

But you also need to ensure that _session is disposed at the end of your program. And you need to make sure you never try to use the _session multiple times in parallel.


If you just want to factor out the Session creation, see:
https://stackoverflow.com/q/74727075/850848

huangapple
  • 本文由 发表于 2023年4月11日 07:19:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75981397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定