Hello, the "sftp server" package supports creating sftp server, please check out the trial version on Nuget https://www.nuget.org/packages/ComponentPro.SftpServer
Example code snippet to setup:
using System;
using ComponentPro.Net.Servers;
using ComponentPro.Net;
using System.IO;
namespace sftp_server
{
class Program
{
static void Main(string[] args)
{
ComponentPro.Licensing.Common.LicenseManager.SetLicenseKey("4D16A969F0F8F1D9E3890245F9D3CEA7FCF3B648B88DABC5C28FDF36");
using (SftpSshServer _server = new SftpSshServer())
{
// Add a private key
SecureShellPrivateKey rsaKey = GenerateOrGetServerKey();
_server.HostKeyStorage.Add(rsaKey);
// Root dir config
string rootDir = AppDomain.CurrentDomain.BaseDirectory;
Directory.CreateDirectory(rootDir);
// Add granted user
AddUser(_server, "test", "test", Path.GetFullPath(rootDir));
// Start listening on port
StartServer(_server, 8888, true);
// Hang (or do something) while listening for connections and serve
while (true)
{
System.Threading.Thread.Sleep(1000);
}
}
}
static int _currentPort = -1;
///
/// Starts or stops the server.
///
///
true to start the server; otherwise false to stop the server.
static void StartServer(SftpSshServer server, int port, bool start)
{
if (start)
{
bool bind = false;
if (_currentPort == -1) // Start the server for the first time?
{
_currentPort = port;
bind = true;
}
else if (port != _currentPort) // If the server port has changed, we need to unbind the old port and bind to the new one.
{
// Unbind the old port.
server.ClosePort(_currentPort);
_currentPort = port;
bind = true;
}
if (bind)
{
// Enable SFTP subsystem
server.OpenPort(_currentPort, FileServerProtocol.Sftp);
// Enable shell-like SCP subsystem
server.OpenPort(_currentPort, FileServerProtocol.Scp);
}
// Start the server
server.Start();
Console.WriteLine("SFTP and SCP file server is running. Port: {0}.", port);
}
else
{
// Stop the server
server.Stop();
Console.WriteLine("Server has been stopped.");
}
}
static SecureShellPrivateKey GenerateOrGetServerKey()
{
SecureShellPrivateKey rsaKey;
string keyFile = AppDomain.CurrentDomain.BaseDirectory "serverkey.key";
const string keyFilePassword = "pass";
if (!File.Exists(keyFile))
{
// Generate a private key for the server if the key file does not exist.
rsaKey = SecureShellPrivateKey.Create(SecureShellHostKeyAlgorithm.RSA, 1024);
rsaKey.Save(keyFile, keyFilePassword, SecureShellPrivateKeyFormat.Pkcs8);
}
else
{
// Load the key file if it exists.
rsaKey = new SecureShellPrivateKey(keyFile, keyFilePassword);
}
return rsaKey;
}
static void AddUser(SftpSshServer server, string username, string password, string path)
{
// Create a new user with the new virtual root path
FileServerUser user = new FileServerUser(username, password, path);
bool addToList = true;
// If a user with the same username already exists, remove that one.
if (server.Users.Contains(username))
{
server.Users.Remove(username);
addToList = false;
}
// Add the new user.
server.Users.Add(user);
}
}
}