如何在FtpWebRequest之前检查FTP上是否存在文件

Tom*_*ski 66 .net c# ftp ftpwebrequest

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

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

use*_*467 113

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
    }
}
Run Code Online (Sandbox Code Playgroud)

作为一般规则,在代码中使用Exceptions作为功能是一个坏主意,但在这种情况下,我认为这是实用主义的胜利.通过这种方式使用异常,目录上的调用列表可能比FAR更低效.

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

编辑:"这对我有用!"

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

request.UseBinary = true;
Run Code Online (Sandbox Code Playgroud)

不幸的是,这是一个设计限制(大胖虫!),除非FtpWebRequest下载或上传文件,否则它不会发送"TYPE I".请在此处查看讨论和Microsoft响应.

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

WebRequestMethods.Ftp.GetDateTimestamp
Run Code Online (Sandbox Code Playgroud)

  • 你真的是个天才!它就像一个魅力! (2认同)
  • @Dan您是否尝试过:request.KeepAlive = true; ? (2认同)

小智 8

因为

request.Method = WebRequestMethods.Ftp.GetFileSize
Run Code Online (Sandbox Code Playgroud)

在某些情况下可能会失败(550:在ASCII模式下不允许SIZE),您可以只检查时间戳.

reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
Run Code Online (Sandbox Code Playgroud)


Mar*_*ryl 5

FtpWebRequest(也不是 .NET 中的任何其他类)没有任何显式方法来检查 FTP 服务器上的文件是否存在。您需要滥用像GetFileSize或 之类的请求GetDateTimestamp

string url = "ftp://ftp.example.com/remote/path/file.txt";

WebRequest request = WebRequest.Create(url);
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.GetFileSize;
try
{
    request.GetResponse();
    Console.WriteLine("Exists");
}
catch (WebException e)
{
    FtpWebResponse response = (FtpWebResponse)e.Response;
    if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
    {
        Console.WriteLine("Does not exist");
    }
    else
    {
        Console.WriteLine("Error: " + e.Message);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想要更直接的代码,请使用一些 3rd 方 FTP 库。

例如对于WinSCP .NET 程序集,您可以使用其Session.FileExists方法

SessionOptions sessionOptions = new SessionOptions {
    Protocol = Protocol.Ftp,
    HostName = "ftp.example.com",
    UserName = "username",
    Password = "password",
};

Session session = new Session();
session.Open(sessionOptions);

if (session.FileExists("/remote/path/file.txt"))
{
    Console.WriteLine("Exists");
}
else
{
    Console.WriteLine("Does not exist");
}
Run Code Online (Sandbox Code Playgroud)

(我是 WinSCP 的作者)