简体   繁体   中英

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)

Example: I want to check if in the folder /testftp contains a textfile.txt file.

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.

Probably less work than filtering the result of 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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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