如何在 FtpWebRequest 之前检查 FTP 上是否存在文件 [英] How to check if file exists on FTP before FtpWebRequest

查看:32
本文介绍了如何在 FtpWebRequest 之前检查 FTP 上是否存在文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 FtpWebRequest 将文件放入 FTP 目录.在上传之前,我首先想知道这个文件是否存在.

I need to use FtpWebRequest to put a file in a FTP directory. Before the upload, I would first like to know if this file exists.

我应该使用什么方法或属性来检查这个文件是否存在?

What method or property should I use to check if this file exists?

推荐答案

var request = (FtpWebRequest)WebRequest.Create
    ("ftp://ftp.domain.com/doesntexist.txt");
request.Credentials = new NetworkCredential("user", "pass");
request.Method = WebRequestMethods.Ftp.GetFileSize;

try
{
    FtpWebResponse response = (FtpWebResponse)request.GetResponse();
}
catch (WebException ex)
{
    FtpWebResponse response = (FtpWebResponse)ex.Response;
    if (response.StatusCode ==
        FtpStatusCode.ActionNotTakenFileUnavailable)
    {
        //Does not exist
    }
}

一般来说,在你的代码中使用异常是一个坏主意,但是在这种情况下,我相信这是实用主义的胜利.在目录上调用列表可能比以这种方式使用异常效率低得多.

As a general rule it's a bad idea to use Exceptions for functionality in your code like this, however in this instance I believe it's a win for pragmatism. Calling list on the directory has the potential to be FAR more inefficient than using exceptions in this way.

如果你不是,请注意这不是一个好习惯!

If you're not, just be aware it's not good practice!

它对我有用!"

这似乎适用于大多数 ftp 服务器,但不是全部.有些服务器需要在 SIZE 命令起作用之前发送TYPE I".有人会认为问题应该如下解决:

This appears to work on most ftp servers but not all. Some servers require sending "TYPE I" before the SIZE command will work. One would have thought that the problem should be solved as follows:

request.UseBinary = true;

不幸的是,这是一个设计限制(大胖错误!),除非 FtpWebRequest 正在下载或上传文件,否则它不会发送TYPE I".查看讨论和 Microsoft 回复 这里.

Unfortunately it is a by design limitation (big fat bug!) that unless FtpWebRequest is either downloading or uploading a file it will NOT send "TYPE I". See discussion and Microsoft response here.

我建议改用以下 WebRequestMethod,这适用于我测试的所有服务器,即使是不会返回文件大小的服务器.

I'd recommend using the following WebRequestMethod instead, this works for me on all servers I tested, even ones which would not return a file size.

WebRequestMethods.Ftp.GetDateTimestamp

这篇关于如何在 FtpWebRequest 之前检查 FTP 上是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆