如何将FTP网络文件夹挂载为本地磁盘?附C#实现代码
问题:将FTP网络文件夹挂载为本地磁盘
我想把FTP网络文件夹挂载成本地磁盘,就像Google Drive那样把网络驱动器挂载到本地。这是我第一次接触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<PSObject> 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 <= 'Z'; letter++) { if (IsLetterAvailable(letter)) { return letter; } } return '0'; }
希望能得到相关帮助!
内容的提问来源于stack exchange,提问作者Hugo Jiménez
相关产品推荐
相关产品推荐

