无法对 FTP 文件夹使用 GetDateTimestamp

Cannot use GetDateTimestamp for FTP folder

我接收时间戳的代码

// Try to get the LastModified date of the folder whose existence has to be checked

// Get the object used to communicate with the server.  
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(DirectoryPath));
request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
request.Credentials = new NetworkCredential(_username, _password);

//Step-1: This line will decide if the Directory exists or not
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Status-1: " + response.StatusDescription);
Console.WriteLine("Last Modified: " + response.LastModified);

validDirectory = true;
response.Close();

问题: 如果我使用另一台 Windows PC 作为 FTP 服务器(使用 FileZilla),以上代码工作正常。但是,如果我尝试使用上述代码从在线 FTP 服务器 (wwww.driveHQ.com) 获取时间戳,则行 FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 会引发异常:

The remote server returned an error: <550> File unavailable (e.g. file not found, no access)

PS: 我能够连接到服务器(获得状态代码:150,连接已接受)。我的 Uri 也是正确的(我能够成功地创建一个目录)。 仅当我尝试获取此创建目录的时间戳或尝试获取目录内的文件列表时才会出现问题。

GetDateTimestamp 方法在下面使用 FTP MDTM 命令。

许多 FTP 服务器,包括 IIS 或 DriveHQ,不支持文件夹的 MDTM 命令。


检索修改时间的其他方法是 MLST 命令。但这不受 FtpWebRequest 支持。您将不得不使用不同的 FTP 客户端库(例如我的 WinSCP .NET assembly and its Session.GetFileInfo method)。

但这对你也没有多大帮助。许多服务器根本不支持 MLST 命令(例如 IIS)。 DriveHQ returns 格式错误(恕我直言)对 MLST 命令的响应。虽然它包含修改时间,但它不包含文件名,WinSCP 无法解析响应。您将不得不进行一些粗暴的破解,例如解析 WinSCP 会话日志文件以从中获取修改时间戳。或者也许另一个第 3 方库将能够处理 DriveHQ 响应。


最后一个选项是完整列出父目录,从列表中检索子目录的时间戳。

虽然这不是很好的解决方案是一般的,因为FtpWebRequest只支持LIST命令,没有标准格式,DriveHQ使用比较标准的*nix格式,所以你可以例如使用我对 Parsing FtpWebRequest ListDirectoryDetails line.

的回答

虽然您实际使用 GetDateTimestamp 只是为了检查文件夹是否存在,但您可以简单地使用 ListDirectory 方法而不是 GetDateTimestamp。这显然是一种矫枉过正,但它是迄今为止最简单的解决方案,具有 FtpWebRequest 和 DriveHQ 的综合限制。

参见 How to check if an FTP Directory Exists