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

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

问题描述

我需要使用的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这样的,但是在这种情况下,我相信这是一个双赢的务实精神。调用列表中的目录应该远比使用异常以这种方式效率较低的潜力。

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

编辑:它为我的作品!

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

  request.UseBinary = TRUE;
 

不幸的是它是一个由设计限制(大发错误!),除非的FtpWebRequest或者是下载或上传文件它将不会发出我型。见讨论和微软响应<一href="http://social.msdn.microsoft.com/forums/en-US/netfxnetcom/thread/0c38814e-d8e3-49f3-8818-b5306cc100ce/">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

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

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