如何检查文件的FtpWebRequest之前存在于FTP文件、FtpWebRequest、FTP

由网友(痛的余味)分享简介:我需要使用的FtpWebRequest把一个文件中的一个FTP目录。上传之前,我想先知道,如果这个文件存在。 我应该使用什么方法或属性检查这个文件是否存在?解决方案 VAR请求=(的FtpWebRequest)WebRequest.Create(ftp://ftp.domain.com/doesntexist.t...

我需要使用的FtpWebRequest把一个文件中的一个FTP目录。上传之前,我想先知道,如果这个文件存在。

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

解决方案

  VAR请求=(的FtpWebRequest)WebRequest.Create
    (ftp://ftp.domain.com/doesntexist.txt);
request.Credentials =新的NetworkCredential(用户,通行证);
request.Method = WebRequestMethods.Ftp.GetFileSize;

尝试
{
    FtpWebResponse响应=(FtpWebResponse)request.GetResponse();
}
赶上(WebException前)
{
    FtpWebResponse响应=(FtpWebResponse)ex.Response;
    如果(response.Status code ==
        FtpStatus code.ActionNotTakenFileUnavailable)
    {
        //不存在
    }
}
 

一般情况下这是一个坏主意,使用例外功能,在您的code这样的,但是在这种情况下,我相信这是一个双赢的务实精神。调用列表中的目录应该远比使用异常以这种方式效率较低的潜力。

如果你不是,只是知道这不是好习惯!

编辑:它为我的作品!

如何使用ie浏览器查看ftp站点并下载文件

这似乎适用于大多数的FTP服务器,但不是全部。有些服务器需要发送I型之前大小命令会工作。人们会认为,这个问题应该得到解决如下:

  request.UseBinary = TRUE;
 

不幸的是它是一个由设计限制(大发错误!),除非的FtpWebRequest或者是下载或上传文件它将不会发出我型。见讨论和微软响应here.

我会建议使用以下WebRequestMethod代替,这对我的作品的所有服务器我测试,甚至是那些这将不会返回文件大小。

  WebRequestMethods.Ftp.GetDateTimestamp
 

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!

EDIT: "It works for me!"

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;

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.

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

阅读全文

相关推荐

最新文章