0

I am trying to catch the Access Denied Exception when trying to upload a file via FTP using FluentFTP

try
{
    client = new FtpClient(serverName, userName, password);
    client.AutoConnect();
    client.RetryAttempts = 3;
    client.UploadFile(localPath, serverPath, FtpRemoteExists.Overwrite, false,FtpVerify.Retry);

}
catch (Exception ex)
{
    if (ex is FtpException && ex.InnerException?.Message == "Access is denied. ")
    {
        //Do something here
        throw ex;
    }
    throw;
}

I cannot rely on "Access is denied. " on this string but I don't know how to catch that Exception.

1 Answers1

0

I would recommend that you check the directory before moving on to upload:

if (!client.DirectoryExists(serverPath))
{
   //do somthing...
}

you can also try to get the permission of file/directory and catch exception thrown by it:

try
{
  ...
  var ftpListItem = client.GetFilePermissions(pathOnTheServer);
  if (ftpListItem.GroupPermissions == FtpPermission.None ||
      ftpListItem.OthersPermissions == FtpPermission.None
      ) //or other permission category..
  {
     //do something...
     return;
  }


  //do other things..

 }
 catch (FtpCommandException ex) //get permission failed 
 {
    //handle exception 
 }
 catch(Exception ex) 
 { 
    //hendel other exceptions
 }

Bounce: you can use using statement to properly dispose the client after done using it:

using (var client = new FtpClient(serverName, userName, password))
{
    //your code...
}
Somar Zein
  • 170
  • 6
  • GetFilePermissions returns None for all the groups even I can read and write on that particular folder. – Petri Adrian Apr 01 '22 at 10:39
  • `FtpPermission.None` = No access, which give you a hint that the **no access exception** would be thrown (which is i think the answer to your question). on the other hand, when you say the you can read and write; then what do you mean by **I**? do you do it using UI? or in the same project that you are working on? – Somar Zein Apr 01 '22 at 12:26