Renci SSH.NET:是否可以创建包含不存在的子文件夹的文件夹

我目前正在使用Renci SSH.NET使用SFTP将文件和文件夹上传到Unix服务器,并使用创建目录

sftp.CreateDirectory("//server/test/test2"); 

只要文件夹“test”已经存在,它就能完美运行。 如果没有, CreateDirectory方法将失败,并且每次尝试创建包含多个级别的目录时都会发生这种情况。

是否有一种优雅的方式来递归生成字符串中的所有目录? 我假设CreateDirectory方法自动执行此操作。

别无他法。

只需迭代目录级别,使用SftpClient.GetAttributes测试每个级别并创建不存在的级别。

 static public void CreateDirectoryRecursively(this SftpClient client, string path) { string current = ""; if (path[0] == '/') { path = path.Substring(1); } while (!string.IsNullOrEmpty(path)) { int p = path.IndexOf('/'); current += '/'; if (p >= 0) { current += path.Substring(0, p); path = path.Substring(p + 1); } else { current += path; path = ""; } try { SftpFileAttributes attrs = client.GetAttributes(current); if (!attrs.IsDirectory) { throw new Exception("not directory"); } } catch (SftpPathNotFoundException) { client.CreateDirectory(current); } } } 

Martin Prikryl提供的代码略有改进

不要将Exceptions用作流控制机制。 这里更好的选择是先检查当前路径是否存在。

 if (client.Exists(current)) { SftpFileAttributes attrs = client.GetAttributes(current); if (!attrs.IsDirectory) { throw new Exception("not directory"); } } else { client.CreateDirectory(current); } 

而不是try catch构造

 try { SftpFileAttributes attrs = client.GetAttributes(current); if (!attrs.IsDirectory) { throw new Exception("not directory"); } } catch (SftpPathNotFoundException) { client.CreateDirectory(current); } 

FWIW,这是我相当简单的看法。 一个要求是服务器目标路径由正斜率分隔,这是常态。 我在调用函数之前检查了这个。

  private void CreateServerDirectoryIfItDoesntExist(string serverDestinationPath, SftpClient sftpClient) { if (serverDestinationPath[0] == '/') serverDestinationPath = serverDestinationPath.Substring(1); string[] directories = serverDestinationPath.Split('/'); for (int i = 0; i < directories.Length; i++) { string dirName = string.Join("/", directories, 0, i + 1); if (!sftpClient.Exists(dirName)) sftpClient.CreateDirectory(dirName); } } 

HTH