C # 4: check if FTP directory exists

I used the class for all my FTP transmissions that work fine in C # 3.5, but since I upgraded to framework 4, I have some problems.

I searched on Google but did not find any solutions.

Specifically using the directory check method:

public bool DirectoryExists(string directory)
{
  bool directoryExists = false;
  if (directory.Substring(0, 1) != "/")
    directory = "/" + directory;
  FtpWebRequest request = GetFtpWebRequest(host + directory, WebRequestMethods.Ftp.PrintWorkingDirectory);
  try
  {
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
    {
      directoryExists = true;
    }
  }
  catch (WebException)
  {
    directoryExists = false;
  }
  return directoryExists;
}

private FtpWebRequest GetFtpWebRequest(string url, string method)
{
  FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
  request.UseBinary = true;
  request.KeepAlive = true;
  request.UsePassive = (mode == Modes.Passive);
  request.Timeout = Timeout.Infinite;
  request.ServicePoint.ConnectionLimit = 6;
  request.ReadWriteTimeout = Timeout.Infinite;
  if (credential == null)
    credential = new NetworkCredential(login, password);
  request.Credentials = credential;
  request.Method = method;
  return request;
}

The DirectoryExists method always returns true (even the directory does not exist), but only in framework 4 before the exception was thrown by GetFtpWebRequest if the directory does not exist.

Has anyone had this problem?

Please do not tell me to use another library, because all my programs depend on this, and I do not want to update everything ...

+3
source share
2 answers

, (4.0) 'CWD'. SetMethodRequiresCWD() Microsoft https://support.microsoft.com/en-us/kb/2134299

+1

:

WebRequestMethods.Ftp.PrintWorkingDirectory

to...

WebRequestMethods.Ftp.ListDirectory

.NET 4.0.

+2

Source: https://habr.com/ru/post/1788998/


All Articles