C# 4:如何检查FTP目录是否存在

3

我在C# 3.5中使用一个类来进行所有FTP传输,效果很好,但是自从我升级到4框架后,出现了一些问题。

我在Google上搜索,但没有找到解决方案。

尤其是关于检查目录是否存在的方法:

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(即使目录不存在),但仅适用于框架4,在此之前,如果目录不存在,则GetFtpWebRequest会引发异常。

有人遇到过这个问题吗?

请不要告诉我使用另一个库,因为我所有的程序都依赖于这个库,我不想更新所有的程序...


1
你尝试过在返回TRUE之前检查响应的内容吗? - Panagiotis Kanavos
1
你更新了你的项目到.NET 4.0吗?如果是这样,请检查在项目属性中是否使用了.NET 4.0框架而不是.NET 4.0客户端配置文件。这已经解决了我遇到的大约75%的兼容性问题。 - Weegee
是的,我将项目更新到“.NET Framework 4”。如果我使用“.NET Framework 3.5”,那就没问题了。 在“.NET Framework 4”上,如果目录存在或不存在,响应状态码始终为“PathnameCreated”... - A.Baudouin
经过多次测试,似乎在框架4中,PrintWorkingDirectory方法始终返回“/”(无论目录是否存在)。 我的FTP服务器在Ubuntu上... - A.Baudouin
2个回答

2

只需将:

WebRequestMethods.Ftp.PrintWorkingDirectory

更改为...

WebRequestMethods.Ftp.ListDirectory

您的代码就可以在.NET 4.0中正常运行。


是的,这就是我所做的。 但是进行这个测试需要的时间大约是原来的20倍,这对我的FTP应用程序来说是一个真正的问题... - A.Baudouin

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接