我正在使用 SSH.NET 将 SFTP 文件从一台服务器传输到另一台服务器。我正在使用 C# .NET 4.5 MVC 4。它工作得很好,除非有多个请求尝试上传文件,此时我收到一个错误,即 SSH 私钥当前正在被另一个进程使用。我假设一个请求设置了从私钥文件读取的 ConnectionInfo 对象,而另一个请求在第一个请求完成从该文件读取之前尝试做同样的事情。
有什么帮助吗?
请注意,在下面的代码中,我已将“test”添加到所有字符串 obj 值。在生产中,情况并非如此。
谢谢!
public class SftpService : ISftpService
{
private static ConnectionInfo _sftpConnectionInfo { get; set; }
private static readonly string _mediaServerHost = "test";
private static readonly string _mediaServerUsername = "test";
private static readonly int _mediaServerPort = 22;
private static readonly string _privateSshKeyLocation = "test";
private static readonly string _privateSshKeyPhrase = "test";
private static readonly string _mediaServerUploadRootLocation = "test";
public SftpService()
{
var authenticationMethod = new PrivateKeyAuthenticationMethod(_mediaServerUsername, new PrivateKeyFile[]{
new PrivateKeyFile(_privateSshKeyLocation, _privateSshKeyPhrase)
});
// Setup Credentials and Server Information
_sftpConnectionInfo = new ConnectionInfo(_mediaServerHost, _mediaServerPort, _mediaServerUsername,
authenticationMethod
);
}
public void UploadResource(Stream fileStream)
{
using (var sftp = new SftpClient(_sftpConnectionInfo))
{
sftp.Connect();
//this is not the real path, just showing example
var path = "abc.txt";
sftp.UploadFile(fileStream, path, true);
sftp.Disconnect();
}
}
}