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
How can I check if I have the rights to create subdirs?
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.
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);
}
}
}
You are correct. You cannot create an entire path in one command to FTP. The simplest way to do is probably as follows:
- Create a make directory method that accepts the Uri.
- Make sure that you can differentiate between errors where part of the path doesn't exist and other errors.
- If it's anything but a path error, rethrow the exception.
- If it's a path error:
- Trim the last directory from the path.
- If there's nothing more to trim quit by throwing an appropriate new exception.
- Try to create the new path.
- 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.