Я впервые работаю с FTP и сетью соединения.
Читаю другие ответы и форумы. У меня установлены следующие пакеты NuGet:
- Cake.Powershell
- FluentFTP
- Microsoft.Management.Infrastructure
Код: Выделить всё
private void bAnadir_Click(object sender, EventArgs e)
{
string remotePath = @"ftpPath";
string username = "user";
string password = "paswrd";
char driveLetter = 'S';
driveLetter = FirstAvailableLetter(driveLetter);
MountFTP(remotePath, username, password, driveLetter);
MessageBox.Show($"FTP '{remotePath}' was mounted as drive {driveLetter}: successfully.");
}
private void MountFTP(string ftpPath, string username, string password, char driveLetter)
{
string cmd = $"New-PSDrive -Name {driveLetter} -PSProvider FileSystem -Root {ftpPath} -Credential (New-Object System.Management.Automation.PSCredential('{username}', (ConvertTo-SecureString '{password}' -AsPlainText -Force)))";
RunPowerShellCommand(cmd);
}
private void RunPowerShellCommand(string command)
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript(command);
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
PowerShellInstance.Runspace = RunspaceFactory.CreateRunspace(connectionInfo);
PowerShellInstance.Runspace.Open();
Collection
PSOutput = PowerShellInstance.Invoke();
foreach (PSObject outputItem in PSOutput)
{
if (outputItem != null)
{
Console.WriteLine(outputItem.BaseObject.GetType().FullName);
Console.WriteLine(outputItem.BaseObject.ToString() + "\n");
}
}
if (PowerShellInstance.Streams.Error.Count > 0)
{
foreach (ErrorRecord error in PowerShellInstance.Streams.Error)
{
MessageBox.Show($"Error: {error.Exception.Message}");
}
}
}
}
static bool IsLetterAvailable(char driveLetter)
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo drive in allDrives)
{
if (drive.IsReady && string.Equals(drive.Name.Substring(0, 1), driveLetter.ToString(), StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}
static char FirstAvailableLetter(char preferredDriveLetter)
{
char driveLetter = preferredDriveLetter;
if (IsLetterAvailable(driveLetter))
{
return driveLetter;
}
for (char letter = 'D'; letter
Подробнее здесь: [url]https://stackoverflow.com/questions/78681636/how-to-mount-ftp-folder-as-local-disk[/url]