68

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

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

4

5 回答 5

118
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
    }
}

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

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

编辑:“它对我有用!”

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

request.UseBinary = true;

不幸的是,这是一个设计限制(大胖错误!),除非 FtpWebRequest 正在下载或上传文件,否则它不会发送“TYPE I”。请参阅此处的讨论和 Microsoft 回复。

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

WebRequestMethods.Ftp.GetDateTimestamp
于 2008-12-07T23:40:38.887 回答
9

因为

request.Method = WebRequestMethods.Ftp.GetFileSize

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

reqFTP.Credentials = new NetworkCredential(inf.LogOn, inf.Password);
reqFTP.UseBinary = true;
reqFTP.Method = WebRequestMethods.Ftp.GetDateTimestamp;
于 2015-09-16T15:39:41.903 回答
5

FtpWebRequest(也不是 .NET 中的任何其他类)没有任何显式方法来检查 FTP 服务器上的文件是否存在。您需要滥用类似GetFileSizeor的请求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);
    }
}

如果您想要更直接的代码,请使用一些 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");
}

(我是WinSCP的作者)

于 2018-04-27T06:52:36.190 回答
0

您可以使用WebRequestMethods.Ftp.ListDirectory来检查文件是否存在,不需要讨厌的 try catch 机制。

    private static bool ExistFile(string remoteAddress)
    {
        int pos = remoteAddress.LastIndexOf('/');
        string dirPath = remoteAddress.Substring(0, pos); // skip the filename only get the directory

        NetworkCredential credentials = new NetworkCredential(FtpUser, FtpPass);
        FtpWebRequest listRequest = (FtpWebRequest)WebRequest.Create(dirPath);
        listRequest.Method = WebRequestMethods.Ftp.ListDirectory;
        listRequest.Credentials = credentials;
        using (FtpWebResponse listResponse = (FtpWebResponse)listRequest.GetResponse())
        using (Stream listStream = listResponse.GetResponseStream())
        using (StreamReader listReader = new StreamReader(listStream))
        {
            string fileToTest = Path.GetFileName(remoteAddress);
            while (!listReader.EndOfStream)
            {
                string fileName = listReader.ReadLine();
                fileName = Path.GetFileName(fileName);
                if (fileToTest == fileName)
                {
                    return true;
                }

            }
        }
        return false;
    }

    static void Main(string[] args)
    {
        bool existFile = ExistFile("ftp://123.456.789.12/test/config.json");
    }
于 2021-08-11T07:57:32.193 回答
-1

我使用 FTPStatusCode.FileActionOK 来检查文件是否存在......

然后,在“else”部分,返回 false。

于 2017-12-09T21:51:25.110 回答