Ftp.MakeDirectory nested structure

2019-04-15 16:28发布

What do you guys do if you lack of permissions to create subdirs on a ftp? Apparently you can't create a directory in one command

So this:

path = "ftp://someftp.com/files/newFolder/innerFolder";
var request = (FtpWebRequest)WebRequest.Create(path);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
var response = (FtpWebResponse)request.GetResponse());

will throw an exception with error code 550 if 'files' or 'newFolder' is already exists

  1. How can I check if I have the rights to create subdirs?

  2. What can I do if I don't have those rights? Show me please code that lets you create a folder structure in more than one command.

标签: c# ftp
2条回答
啃猪蹄的小仙女
2楼-- · 2019-04-15 17:09

Alright: because FtpWebRequest is stateless - there is no way to change current directory on FTP. Fortunately we can use one of the open-source FTP libraries. Here's an example with AlexPilotti's FTPS library, which is availible through NuGet

using (var client = new FTPSClient())
{
     var address = Regex.Match(path, @"^(ftp://)?(\w*|.?)*/").Value.Replace("ftp://", "").Replace("/", "");
     var dirs = Regex.Split(path.Replace(address, "").Replace("ftp://", ""), "/").Where(x => x.Length > 0);
     client.Connect(address, credential, ESSLSupportMode.ClearText);
     foreach (var dir in dirs)
     {
        try
           {
              client.MakeDir(dir);
           }
        catch (FTPException)
        {
        }
        client.SetCurrentDirectory(dir);
     }

   }
}
查看更多
家丑人穷心不美
3楼-- · 2019-04-15 17:12

You are correct. You cannot create an entire path in one command to FTP. The simplest way to do is probably as follows:

  1. Create a make directory method that accepts the Uri.
  2. Make sure that you can differentiate between errors where part of the path doesn't exist and other errors.
  3. If it's anything but a path error, rethrow the exception.
  4. If it's a path error:
  5. Trim the last directory from the path.
  6. If there's nothing more to trim quit by throwing an appropriate new exception.
  7. Try to create the new path.
  8. Then try to create the final directory again.

So essentially, it becomes recursive with two limit conditions, non-path exceptions occurring and nothing left to trim.

查看更多
登录 后发表回答