c#4:检查FTP目录是否存在

c#4:检查FTP目录是否存在,c#,ftp,C#,Ftp,我所有的FTP传输都使用了一个类,它在C#3.5中工作得很好,但是由于我升级到了Framework4,我遇到了一些问题 我在谷歌上搜索,但没有找到解决方案 特别是使用检查目录是否存在的方法: public bool DirectoryExists(string directory) { bool directoryExists = false; if (directory.Substring(0, 1) != "/") directory = "/" + directory;

我所有的FTP传输都使用了一个类,它在C#3.5中工作得很好,但是由于我升级到了Framework4,我遇到了一些问题

我在谷歌上搜索,但没有找到解决方案

特别是使用检查目录是否存在的方法:

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;
}
DirectoryExists方法始终返回true(即使该目录不存在),但仅在framework 4上返回,如果该目录不存在,则GetFTPWebreRequest会引发异常

有人有这个问题吗

请不要告诉我使用其他库,因为我的所有程序都依赖于此库,我不想全部更新…

只需更改:

WebRequestMethods.Ftp.PrintWorkingDirectory

WebRequestMethods.Ftp.ListDirectory


您的代码在.NET 4.0中也可以正常工作。

问题在于,在新的实现(4.0)中,客户端不发送命令“CWD”。从这里使用方法SetMethodRequiresCWD() 微软分辨率

在返回TRUE之前,您是否尝试过检查响应的内容;您是否将项目更新为.NET 4.0?如果是这样,请在项目属性中检查您使用的是.NET 4.0框架,而不是.NET 4.0客户端配置文件。这已经解决了我到目前为止遇到的75%的兼容性问题。如果我使用“.NETFramework 3.5”就可以了。在“.NET framework 4”上,如果目录存在或不存在,则响应状态代码始终为“PathnameCreated”…经过多次测试,在framework 4中,PrintWorkingDirectory方法似乎总是返回“/”(如果目录存在或不存在)。我的FTP服务器在Ubuntu上…是的,这就是我所做的。但是做这个测试要多花20倍的时间,这对我的FTP应用程序来说是一个真正的问题。。。