Creating a project
mkdir TestGenericHost
cd TestGenericHost
dotnet new console
Adding the NuGet packages
# For dependency injection support (required)
dotnet add package Microsoft.Extensions.DependencyInjection
# For the main FTP server
dotnet add package FubarDev.FtpServer
# For the System.IO-based file system access
dotnet add package FubarDev.FtpServer.FileSystem.DotNet
Create an IHostedService
implementation
Important
This is only required for version 3.0, because the FTP server will provide a much tighter ASP.NET Core integration in a future release.
Create a new file named HostedFtpService.cs
, which contains the following code:
using System.Threading;
using System.Threading.Tasks;
using FubarDev.FtpServer;
using Microsoft.Extensions.Hosting;
namespace TestGenericHost
{
internal class HostedFtpService : IHostedService
{
private readonly IFtpServerHost _ftpServerHost;
/// <summary>
/// Initializes a new instance of the <see cref="HostedFtpService"/> class.
/// </summary>
/// <param name="ftpServerHost">The FTP server host that gets wrapped as a hosted service.</param>
public HostedFtpService(
IFtpServerHost ftpServerHost)
{
_ftpServerHost = ftpServerHost;
}
/// <inheritdoc />
public Task StartAsync(CancellationToken cancellationToken)
{
return _ftpServerHost.StartAsync(cancellationToken);
}
/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
return _ftpServerHost.StopAsync(cancellationToken);
}
}
}
Using the FTP server
Change your Program.cs
to the following code:
using System;
using System.IO;
using System.Threading.Tasks;
using FubarDev.FtpServer;
using FubarDev.FtpServer.FileSystem.DotNet;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace TestGenericHost
{
class Program
{
static Task Main()
{
var hostBuilder = new HostBuilder()
.UseConsoleLifetime()
.ConfigureServices(
(hostContext, services) =>
{
// Add FTP server services
// DotNetFileSystemProvider = Use the .NET file system functionality
// AnonymousMembershipProvider = allow only anonymous logins
services
.AddFtpServer(builder => builder
.UseDotNetFileSystem()
.EnableAnonymousAuthentication());
// Configure the FTP server
services.Configure<FtpServerOptions>(opt => opt.ServerAddress = "127.0.0.1");
// use %TEMP%/TestFtpServer as root folder
services.Configure<DotNetFileSystemOptions>(opt => opt
.RootPath = Path.Combine(Path.GetTempPath(), "TestFtpServer"));
// Add the FTP server as hosted service
services
.AddHostedService<HostedFtpService>();
});
var host = hostBuilder.Build();
return host.RunAsync();
}
}
}
Starting the FTP server
dotnet run
Now your FTP server should be accessible at 127.0.0.1:21
.