Renci SSH.NET:是否可以创建一个包含不存在的子文件夹的文件夹 [英] Renci SSH.NET: Is it possible to create a folder containing a subfolder that does not exist
问题描述
我目前正在使用Renci SSH.NET通过SFTP将文件和文件夹上载到Unix服务器,并使用
I am currently using Renci SSH.NET to upload files and folders to a Unix Server using SFTP, and creating directories using
sftp.CreateDirectory("//server/test/test2");
只要文件夹"test"已经存在,
即可正常工作.如果不是,则CreateDirectory
方法将失败,并且每次尝试创建包含多个级别的目录时都会发生这种情况.
works perfectly, as long as the folder "test" already exists. If it doesn't, the CreateDirectory
method fails, and this happens everytime when you try to create directories containing multiple levels.
是否存在一种优雅的方式来递归地生成字符串中的所有目录?我以为CreateDirectory
方法是自动执行此操作的.
Is there an elegant way to recursively generate all the directories in a string? I was assuming that the CreateDirectory
method does that automatically.
推荐答案
没有其他方法.
只需迭代目录级别,使用SftpClient.GetAttributes
测试每个级别并创建不存在的级别.
Just iterate directory levels, testing each level using SftpClient.GetAttributes
and create the levels that does not exist.
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);
}
}
}
这篇关于Renci SSH.NET:是否可以创建一个包含不存在的子文件夹的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!