简体   繁体   English

如何通过FTP检查远程文件夹中是否存在文件?

[英]How to check if file exists in remote folder via FTP?

I want to check remote folder's content, and determine if the particular file exists in this folder (I'm checking only by filename, so chill :D) 我想检查远程文件夹的内容,并确定该文件夹中是否存在特定文件(我仅按文件名进行检查,所以chill:D)

Example: I want to check if in the folder /testftp contains a textfile.txt file. 示例:我想检查/testftp文件夹中/testftp包含textfile.txt文件。

I'm doing this to get folder content: 我这样做是为了获取文件夹内容:

      FtpWebRequest request = (FtpWebRequest)WebRequest.Create("myftpaddress");
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;


        request.Credentials = new NetworkCredential("uid", "pass");

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        Stream responseStream = response.GetResponseStream();
        StreamReader reader = new StreamReader(responseStream);
        Console.WriteLine(reader.ReadToEnd());

        Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

        reader.Close();
        response.Close(); 

it writes in console: 它写在控制台中:

-rw-r--r--   1 6668   userftp 91137 jul 16 23:20 file1.txt
-rw-r--r--   1 468    userftp   137 jul 16 18:40 file2.swf

and it writes full stream response into console, how to get only file names? 并将完整的流响应写入控制台,如何仅获取文件名? Is there an easier way? 有更容易的方法吗?

It would be easier to just try and download the file. 尝试下载文件会更容易。 If you get StatusCode indicating that the file does not exist, you know it was not there. 如果获取到StatusCode指示该文件不存在,则说明该文件不存在。

Probably less work than filtering the result of ListDirectoryDetails . 可能比过滤ListDirectoryDetails的结果要ListDirectoryDetails

Update 更新

To clarify, all you need to do is this: 为了澄清,您需要做的是:

FtpWebResponse response = (FtpWebResponse) request.GetResponse();
bool fileExists = (response.StatusCode != BAD_COMMAND);

I think BAD_COMMAND would be FtpStatusCode .CantOpenData but I'm not sure. 我认为BAD_COMMAND是FtpStatusCode .CantOpenData,但我不确定。 That's easily tested. 这很容易测试。

string listing = reader.ReadToEnd();

// find all occurrences of the fileName and make sure
// it is bounded by white space or string boundary.

int startIndex = 0;
bool exists = false;
while (true)
{
    int index = listing.IndexOf(fileName, startIndex);
    if (index == -1) break;

    int leadingIndex = index - 1;
    int trailingIndex = index + fileName.Length;

    if ((leadingIndex == -1 || Char.IsWhiteSpace(listing[leadingIndex]) &&
        (trailingIndex == list.Length || Char.IsWhiteSpace(listing[trailingIndex]))
    {
        exists = true;
        break;
    }

    startIndex = trailingIndex;
}

Regex version: 正则表达式版本:

string pattern = string.Format("(^|\\s){0}(\\s|$)", Regex.Escape(fileName));
Regex regex = new Regex(pattern);

string listing = reader.ReadToEnd();
bool exists = regex.IsMatch(listing);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM